【问题标题】:Correlation between two dataframes column with matched headers具有匹配标题的两个数据框列之间的相关性
【发布时间】:2019-09-21 13:52:28
【问题描述】:

我有两个来自 excel 的数据框,如下所示。第一个数据帧有一个多索引标头。

我正在尝试根据货币(即 KRW、THB、USD、INR)查找数据帧中的每一列与相应数据帧之间的相关性。目前,我正在循环遍历每一列,在找到相关性之前按索引和相应的标题进行匹配。

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])

有没有更熊猫的方式来做到这一点?

【问题讨论】:

  • 那么,您想为每种货币类型,在另一个数据框中找到相关性吗?建议你多解释一下这两个数据框的结构
  • 我想为第一张图片中的每个“股票”,基于货币与其他数据框的相关性。
  • 你能告诉我两个数据框的整体结构吗?也许,这样,我可以更好地帮助你。
  • 这个问题你解决了吗?

标签: python pandas dataframe


【解决方案1】:

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

# 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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2022-10-13
    • 2022-08-11
    • 2022-06-10
    • 2017-06-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多