【问题标题】:Sum columns of a dataframe iteratively?迭代地对数据框的列求和?
【发布时间】:2020-06-05 01:28:25
【问题描述】:

我正在尝试编写一些代码,将第 1 列和第 2 列相加,并将第 2 列中的值替换为该总和。然后我想添加(新的)第 2 列和第 3 列,并用这两个值的总和替换第 3 列(依此类推)。我确信有更好的方法来解决这个问题,但我认为我需要一些关于如何完成此任务的建议。

Link to a sample of data.

这是我可以执行此操作的手动方式:

dfT = pd.DataFrame({
"Column 1": np.random.rand(4),
"Column 2": np.random.rand(4),
"Column 3": np.random.rand(4),
"Column 4": np.random.rand(4),})

print(dfT.head())

dfT['Column 2'] = dfT.loc[:,'Column 1':'Column 2'].sum(axis = 1)
dfT['Column 3'] = dfT.loc[:,'Column 2':'Column 3'].sum(axis = 1)
dfT['Column 4'] = dfT.loc[:,'Column 3':'Column 4'].sum(axis = 1)
print(dfT.head())

这是两个打印调用的输出:

有没有一个好方法来循环这个过程?我现在正在画一个空白...... 提前感谢您的帮助!

【问题讨论】:

    标签: python-3.x pandas loops math multiple-columns


    【解决方案1】:

    您可以使用DataFrame.cumsum()

    import numpy as np
    import pandas as pd
    
    dfT = pd.DataFrame({
        "Column 1": np.random.rand(4),
        "Column 2": np.random.rand(4),
        "Column 3": np.random.rand(4),
        "Column 4": np.random.rand(4),
    })
    
    print(dfT.head())
    #    Column 1  Column 2  Column 3  Column 4
    # 0  0.744905  0.831893  0.578289  0.759750
    # 1  0.097360  0.436817  0.320901  0.620894
    # 2  0.827297  0.653751  0.607263  0.712541
    # 3  0.826755  0.841087  0.705164  0.738110
    
    print(dfT.cumsum(axis=1))
    #    Column 1  Column 2  Column 3  Column 4
    # 0  0.744905  1.576798  2.155087  2.914837
    # 1  0.097360  0.534177  0.855078  1.475972
    # 2  0.827297  1.481048  2.088311  2.800852
    # 3  0.826755  1.667841  2.373005  3.111115
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2018-08-21
      • 2020-10-16
      • 1970-01-01
      • 2016-01-27
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多