python - 具有匹配标题的两个数据帧列之间的关联

标签 python pandas dataframe

我有两个来自 Excel 的数据框,如下所示。第一个数据帧具有多索引 header 。

我试图找到数据框中每一列与基于货币(即韩元、泰铢、美元、印度卢比)的相应数据框之间的相关性。目前,我正在执行一个循环来迭代每一列,在找到相关性之前按索引和相应的标题进行匹配。

for stock_name in index_data.columns.get_level_values(0):
    stock_prices    = index_data.xs(stock_name, level=0, axis=1)
    stock_prices    = stock_prices.dropna()
    fx              = currency_data[stock_prices.columns.get_level_values(1).values[0]]
    fx              = fx[fx.index.isin(stock_prices.index)]

    merged_df = pd.merge(stock_prices, fx, left_index=True, right_index=True)
    merged_df[0].corr(merged_df[1])

有没有更 Pandas 式的方法来做到这一点?

index_data dataframe

fx dataframe

最佳答案

因此您希望找到股票价格与其相关货币之间的相关性。 (或者股价与所有货币的相关性?)

# dummy data
date_range = pd.date_range('2019-02-01', '2019-03-01', freq='D')

stock_prices = pd.DataFrame(
    np.random.randint(1, 20, (date_range.shape[0], 4)),
    index=date_range,
    columns=[['BYZ6DH', 'BLZGSL', 'MBT', 'BAP'],
            ['KRW', 'THB', 'USD', 'USD']])
fx = pd.DataFrame(np.random.randint(1, 20, (date_range.shape[0], 3)),
                  index=date_range, columns=['KRW', 'THB', 'USD'])

这就是它的样子,计算这些数据的相关性应该没有多大意义,因为它是随机的。

>>> print(stock_prices.head())
           BYZ6DH BLZGSL MBT BAP
              KRW    THB USD USD
2019-02-01     15     10  19  19
2019-02-02      5      9  19   5
2019-02-03     19      7  18  10
2019-02-04      1      6   7  18
2019-02-05     11     17   6   7

>>> print(fx.head())
            KRW  THB  USD
2019-02-01   15   11   10
2019-02-02    6    5    3
2019-02-03   13    1    3
2019-02-04   19    8   14
2019-02-05    6   13    2

使用apply计算具有相同货币的列之间的相关性。

def f(x, fx):
    correlation = x.corr(fx[x.name[1]])
    return correlation

correlation = stock_prices.apply(f, args=(fx,), axis=0)

>>> print(correlation)
BYZ6DH  KRW   -0.247529
BLZGSL  THB    0.043084
MBT     USD   -0.471750
BAP     USD    0.314969
dtype: float64

关于python - 具有匹配标题的两个数据帧列之间的关联,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55962655/

相关文章:

python - 通过将列与多索引组进行比较来过滤 pandas 数据框

默认为 'grandparent' 类实现的 Python 模式

python - 有没有办法在 NumPy 中使数组条目成为复杂变量?

python - Pandas 滚动应用跳过某些值

python - mysql更新整个pandas数据框

python - 与 Pandas 合并后设置索引?

python - python 忽略csv文件中的括号

python - OpenID中store的概念是什么

python - 如何从日期时间对象中仅提取月份和日期?

python - 一旦 df 包含时间序列,Pandas apply with list output 会给出 ValueError