Python 3.x 对数据帧的列进行迭代求和?
我试图编写一些代码,将第1列和第2列相加,并用该总和替换第2列中的值。然后我想添加(新的)第2列和第3列,并将第3列替换为这两个值的总和(依此类推)。我相信有一个更好的方法可以做到这一点,但我想我需要一些关于如何做到这一点的建议 以下是我可以手动执行此操作的方法:Python 3.x 对数据帧的列进行迭代求和?,python-3.x,pandas,loops,math,multiple-columns,Python 3.x,Pandas,Loops,Math,Multiple Columns,我试图编写一些代码,将第1列和第2列相加,并用该总和替换第2列中的值。然后我想添加(新的)第2列和第3列,并将第3列替换为这两个值的总和(依此类推)。我相信有一个更好的方法可以做到这一点,但我想我需要一些关于如何做到这一点的建议 以下是我可以手动执行此操作的方法: dfT = pd.DataFrame({ "Column 1": np.random.rand(4), "Column 2": np.random.rand(4), "Column 3": np.random.rand(4), "C
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())
以下是两个打印调用的输出:
有没有一个好的方法来循环这个过程?我现在一片空白。。。
提前感谢您的帮助 您可以使用
你可以用
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