【问题标题】:Pythonic way of obtaining serial correlation of elements in pandas dataframepythonic获取pandas数据帧中元素序列相关性的方法
【发布时间】:2015-03-11 23:53:22
【问题描述】:

给定一个数据框

A = pd.DataFrame([[1, -5, 2], [2, -4, -4], [3, 3, 1], [-4, 2, -2], [-5, 1, 4]],
                 columns=['A', 'B', 'C'], index=[1, 2, 3, 4, 5])

以pythonic的方式,我怎样才能成对地获得列的连续元素的序列相关性。序列相关很简单:

例如对于A列的第一个元素:

如果元素1A > 0 & 2A > 0 or 1A < 0 & 2A < 0 Serial Correlation = 1

如果元素1A > 0 & 2A < 0 or 1A < 0 & 2A > 0 Serial Correlation = -1

然后您将在列中将每个元素与前一个元素进行比较。

我们的虚拟 df 所需的输出。

   A  B  C
1        
2  1  1 -1
3  1 -1 -1
4 -1  1 -1
5  1  1 -1

然后我会执行serial_corr = df.mean() 之类的操作,以获取列的总 s.correlation。

谢谢

【问题讨论】:

    标签: python python-2.7 pandas dataframe


    【解决方案1】:

    您可以使用DataFrame's shift 方法。注意:如果被比较的任何一个值为 0,这将产生 NaN。

    result = (A.shift() * A).dropna()
    result /= result.abs()
    print(result)
    

    生产

       A  B  C
    2  1  1 -1
    3  1 -1 -1
    4 -1  1 -1
    5  1  1 -1
    

    【讨论】:

    • 非常非常好。谢谢
    猜你喜欢
    • 1970-01-01
    • 2011-02-19
    • 2021-03-05
    • 2022-01-24
    • 1970-01-01
    • 2014-01-28
    • 2018-06-04
    • 2018-09-27
    • 1970-01-01
    相关资源
    最近更新 更多