python - 将 Pandas 中的滚动相关输出简化为单个索引数据帧

标签 python pandas dataframe correlation

我有一个大小合理的时间序列数据 DataFrame,我希望以合理的格式滚动成对相关数据。

Pandas 有一个非常有趣的“滚动”功能,可以进行正确的计算

dfCorrelations = dfReturns.rolling(correlation_window).corr()

但是相关网格的输出时间序列对我以后的使用不方便(显示给定日期的子集的示例输出)。

enter image description here

有没有办法进行相同的计算,但在简单的时间序列 DataFrame 中获取仅具有独特非对角相关性的输出?使用看起来像这样的列索引

['III LN x ABN NA', 'III LN x AGN NA', 'III LN x AGS BB', 'ABN NA x AGN NA', 'ABN NA x AGS BB', ...]

最佳答案

from itertools import combinations

# Create sample dataset.
idx = pd.MultiIndex(
    levels=[[u'2017-1-1', u'2017-1-2'], [u'A', u'B', u'C']],
    labels=[[0, 0, 0, 1, 1, 1], [0, 1, 2, 0, 1, 2]],
    names=[u'date', u'ticker'])
df = pd.DataFrame(np.random.randn(6, 3), index=idx, columns=list('ABC'))
for tup in zip(range(6), range(3) * 2):
    df.iloc[tup] = 1

>>> df
                        A         B         C
date     ticker                              
2017-1-1 A       1.000000  0.440276 -1.087536
         B      -0.809949  1.000000 -0.548897
         C       0.922866 -0.788699  1.000000
2017-1-2 A       1.000000 -0.106493  0.034319
         B       0.080990  1.000000  0.218323
         C       0.051651 -0.680358  1.000000

# Unstack and remove duplicates.
tickers = df.columns.tolist()
df = df.unstack().sort_index(axis=1)
pairs = df.columns.get_values().tolist()
df.columns = ["{0} vs. {1}".format(*pair) for pair in pairs]
mask = [n for n, pair in enumerate(pairs) if pair in list(combinations(tickers, 2))]
df = df.iloc[:, mask]
>>> df
           A vs. B   A vs. C   B vs. C
date                                  
2017-1-1 -0.809949  0.922866 -0.788699
2017-1-2  0.080990  0.051651 -0.680358

关于python - 将 Pandas 中的滚动相关输出简化为单个索引数据帧,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45867895/

相关文章:

python - 将列按名称 move 到 pandas 中的表前面

python - 如何将行字符串值转换为特征

python - 对(删除的)重复行的值求和 Pandas DataFrame

python - 如何重写简单的分词器以使用正则表达式?

python - 如何划分两个DataFrame

Python - 根据其他数据帧列中满足的条件填充 PANDAS 数据帧列

python - Pandas 数据框计数矩阵

python - python数据框中的新向量创建

r - 将值的数据帧转换为二进制数据帧,其中每个唯一值都是一列

python - 为什么稍后绘制圆和多线时不遵守绘图顺序?