【问题标题】:find correlation between pandas time series找到熊猫时间序列之间的相关性
【发布时间】:2020-06-23 03:42:12
【问题描述】:

我有两个 pandas 数据框,我只从一列中获取并将日期列设置为索引,所以现在我有两个 Series。 我需要找出这些系列的相关性

这里有几行来自dfd:

index      change
2018-12-31  -0.86
2018-12-30  0.34
2018-12-27  -0.94
2018-12-26  -1.26
2018-12-25  3.30
2018-12-24  -4.17

来自dfp

index      change
2018-12-31  0.55
2018-12-30  0.81
2018-12-27  -2.99
2018-12-26  0.50
2018-12-25  3.59
2018-12-24  -3.43

我试过了:

correlation=dfp.corr(dfd)

并得到以下错误:

TypeError: unsupported operand type(s) for /: 'str' and 'int'

【问题讨论】:

    标签: python pandas dataframe time-series correlation


    【解决方案1】:

    问题是dfp被数字字符串repr填充,所以使用Series.astype转换为浮点数:

    correlation=dfp.astype(float).corr(dfd.astype(float)
    print (correlation)
    0.8624789983270312
    

    如果某些非数字值解决方案失败,则使用 to_numericerrors='coerce' - 非数字转换为缺失值:

    correlation=pd.to_numeric(dfp, errors='coerce').corr(dfd)
    

    【讨论】:

    • 我收到错误object has no attribute 'corr' 你的两个建议。
    • @SharonAsayag - 所以print (type(dfp))DataFrame
    • 注意 TypeError: unsupported operand type(s) for /: 'str' and 'int' 有问题。我通过以下方式修复了它:correlation=dfp.astype(float).corr(dfd.astype(float))
    • @SharonAsayag - 超级 :)
    【解决方案2】:

    可以合并两个数据框并关联列

    dfd['date']=pd.to_datetime(dfd['date'])
    dfd.set_index(dfd['date'], inplace=True)
    dfd.drop(columns=['date'], inplace=True)
    
    dfp['date']=pd.to_datetime(dfp['date'])
    dfp.set_index(dfp['date'], inplace=True)
    dfp.drop(columns=['date'], inplace=True)
    df = pd.merge(dfp,dfd,left_index=True, right_index=True).reset_index()
    df
    

    关联两列变化(dfd),(dfp)

    df['change(dfp)'].corr(df['change(dfd)'])
    

    结果

    【讨论】:

    • 我收到ValueError: can not merge DataFrame with instance of type <class 'pandas.core.series.Series'>
    • 合并后重置索引。 df = pd.merge(dfp,dfd,left_index=True, right_index=True).reset_index()
    猜你喜欢
    • 2018-06-22
    • 1970-01-01
    • 1970-01-01
    • 2019-11-03
    • 1970-01-01
    • 1970-01-01
    • 2013-06-05
    • 2019-08-19
    • 2018-11-16
    相关资源
    最近更新 更多