我有两个来自 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 式的方法来做到这一点?
最佳答案
因此您希望找到股票价格与其相关货币之间的相关性。 (或者股价与所有货币的相关性?)
# 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/