访问前几行时如何不在df中使用循环

2024-04-26 12:44:43 发布

您现在位置:Python中文网/ 问答频道 /正文

我使用熊猫来处理传输数据。我研究公交线路的出勤率。我有两列来计算在公共汽车的每一站上下车的人数。我想创建一个计算当前机上人数的。目前,我使用一个通过df的回路,对于线n,它是:电流[n]=开[n]-关[n]+电流[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']

有没有办法避免使用循环

谢谢你的时间


2条回答

您可以使用^{},它将给定序列中的数字累加起来

a = pd.DataFrame([[3,4],[6,4],[1,2],[4,5]], columns=["off", "on"])
a["current"] = a["on"].cumsum() - a["off"].cumsum()

   off  on  current
0    3   4        1
1    6   4       -1
2    1   2        0
3    4   5        1

如果我正确地理解了这个问题,您可以计算人们上下车之间的差异,然后使用^{}得到一个运行总数:

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

相关问题 更多 >