我正在尝试编写一些代码,这些代码将遍历并将第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),
"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())下面是两个print调用的输出:

有没有一个很好的方法来循环这个过程呢?我现在一片空白..。提前感谢您的帮助!
发布于 2020-02-21 00:54:48
您可以使用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.111115https://stackoverflow.com/questions/60324725
复制相似问题