我试图捕获一系列周期量的“正在运行”累计和。关于熊猫数据帧的累积和函数
见例如:
df = df[1:4].cumsum() # this doesn't return the desired result
我试图捕获一系列周期量的“正在运行”累计和。关于熊猫数据帧的累积和函数
见例如:
df = df[1:4].cumsum() # this doesn't return the desired result
您正在查找axis
参数。很多Pandas函数都采用这个参数来跨越列或跨行应用操作。使用axis=0
应用行方式,axis=1
应用列方式。这个操作实际上遍历了列,所以你想要axis=1
。
df.cumsum(axis=1)
本身可以在您的示例中生成输出表。
In [3]: df.cumsum(axis=1)
Out[3]:
1 2 3 4
10 16 30 41 61
51 13 29 40 50
13 11 30 45 61
321 12 27 37 52
虽然我怀疑你有兴趣限制到特定范围的列。要做到这一点,你可以使用.loc
与列标签(我的字符串)。
In [4]: df.loc[:, '2':'3'].cumsum(axis=1)
Out[4]:
2 3
10 14 25
51 16 27
13 19 34
321 15 25
.loc
是基于标签并包含边界。如果您想了解更多关于熊猫索引的信息,请查看docs。
你想axis=1
跨行总结。
df.cumsum(axis=1)
侧面说明 - 做[1:4]
切片行默认情况下(即numpy的或列表类似的语义)。如果要按标签选择列,请使用df.loc[:, 1:4]