Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/svg/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 具有匹配标头的两个数据帧列之间的相关性_Python_Pandas_Dataframe - Fatal编程技术网

Python 具有匹配标头的两个数据帧列之间的相关性

Python 具有匹配标头的两个数据帧列之间的相关性,python,pandas,dataframe,Python,Pandas,Dataframe,我有两个来自excels的数据帧,如下所示。第一个数据帧具有多索引头 我试图找出数据框中的每一列与基于货币(即韩元、泰铢、美元、印度卢比)的相应数据框之间的相关性。目前,我正在循环遍历每一列,在找到相关性之前,通过索引和相应的标题进行匹配 for stock_name in index_data.columns.get_level_values(0): stock_prices = index_data.xs(stock_name, level=0, axis=1) sto

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

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

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])
有没有更像熊猫的方法


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

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

>>> 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
用于计算具有相同货币的列之间的相关性

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

那么,您想在另一个数据框中找到每种货币类型的相关性吗?我建议您对第一张图中每个“股票”所需的两个数据帧的结构进行更多的解释,即与基于货币的另一个数据帧的相关性。您能告诉我两个数据帧的整个结构吗??也许,那样的话,我可以帮你更好。你解决这个问题了吗?
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