首页 > 解决方案 > 访问前几行时如何不在df中使用循环

问题描述

我使用 pandas 来处理传输数据。我研究公交线路的出勤率。我有 2 列来计算在公共汽车的每个站点上下车的人数。我想创建一个计算目前在船上的人数。目前,我通过 df 和第 n 行使用循环:current[n]=on[n]-off[n]+current[n-1] 如下例所示:

for index,row in df.iterrows():
if index == 0:
    df.loc[index,'current']=df.loc[index,'on']
else :
    df.loc[index,'current']=df.loc[index,'on']-df.loc[index,'off']+df.loc[index-1,'current']

有没有办法避免使用循环?

谢谢你的时间 !

标签: pythonpandas

解决方案


如果我已经正确理解了这个问题,您可以计算上下车之间的差异,然后使用以下方法计算总和Series.cumsum()

import pandas as pd
# Create dataframe for demo
d = {'Stop':['A','B','C','D'],'On':[3,2,3,2],'Off':[2,1,0,1]}
df = pd.DataFrame(data=d)

# Get difference between 'On' and 'Off' columns.
df['current'] = df['On']-df['Off']

# Get cumulative sum of column
df['Total'] = df['current'].cumsum()



# Same thing in one line
df['Total'] = (df['On']-df['Off']).cumsum()


Stop    On    Off    Total
 A      3      2       1
 B      2      1       2
 C      3      0       5
 D      2      1       6


推荐阅读