【问题标题】:subtract current column value from the previous column of the same row in pandas dataframe从熊猫数据框中同一行的前一列中减去当前列值
【发布时间】:2019-07-29 21:54:48
【问题描述】:

我想从除第一列值之外的同一行(axis=1)的上一列值中减去当前列值

My Dataframe:

   A   B  C  D
0  5  11  4  5
1  3   2  3  4
2  6   4  8  2
3  4   3  5  8

Expected Dataframe:

   A   B  C  D
0  5   6 -2  7
1  3  -1  4  0
2  6  -2  10 12
3  4  -1  6  2

【问题讨论】:

    标签: python-3.x pandas


    【解决方案1】:

    好像没有 cum-diff 的内置函数

    for x, y  in enumerate(df.columns):
        if x ==0 : 
            df[y]=df[y]
        else : 
            df[y]=df[y]-df[df.columns[x-1]]
    
    df
    Out[494]: 
       A  B   C  D
    0  5  6  -2  7
    1  3 -1   4  0
    2  6 -2  10 -8
    3  4 -1   6  2
    

    def cumdiff(df,axis):
        if axis==1 :
            for x, y in enumerate(df.columns):
                if x == 0:
                    df[y] = df[y]
                else:
                    df[y] = df[y] - df[df.columns[x - 1]]
            return df
        else : 
            for x, y in enumerate(df.index):
                if x == 0:
                    df[y] = df[y]
                else:
                    df[y] = df[y] - df[df.columns[x - 1]]
            return df
    
    cumdiff(df,axis=1)
    Out[501]: 
       A  B   C  D
    0  5  6  -2  7
    1  3 -1   4  0
    2  6 -2  10 -8
    3  4 -1   6  2
    

    【讨论】:

    • 嘿,我想要与累积和完全相反的结果..我想要减法。我需要从当前 col 值中减去以前的值(更新的不是原始的)。谢谢
    【解决方案2】:

    您只需使用pandas.DataFrame.expandingreduce function 即可。所以你的代码可以是这样的:

    import pandas as pd
    from functools import reduce
    
    data =  [[5,  11,  4,  5],
             [3,   2,  3,  4],
             [6,   4,  8,  2],
             [4,   3,  5,  8]]
    
    df = pd.DataFrame(data=data, columns=['A','B','C','D'])
    
    print(df)
    >>>   A   B  C  D
       0  5  11  4  5
       1  3   2  3  4
       2  6   4  8  2
       3  4   3  5  8
    
    diff_df = df.expanding(axis=1).apply(lambda x: reduce(lambda a,b : b-a,x)).astype(int)
    
    print(diff_df)
    >>>   A  B   C  D
       0  5  6  -2  7
       1  3 -1   4  0
       2  6 -2  10 -8
       3  4 -1   6  2
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-08-06
      • 2013-12-04
      • 1970-01-01
      • 2014-12-28
      • 1970-01-01
      • 1970-01-01
      • 2017-02-20
      • 2020-12-30
      相关资源
      最近更新 更多