Python:基于另一列的值从一列创建元组

2024-10-03 09:11:47 发布

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

我的数据集如下:

dfTrip:
user_id     status    length
1335         start      0  -> 1st trip starts here
1335         zz         1
1335         zz         7
1335         zz         1
1335         end        5  -> 14 in total for 1st trip
1335         zz         1  -> not added
1335         start      0  -> 2nd trip starts here
1335         zz         4
1335         zz         7
1335         zz         6
1335         end        5  -> 22 in total for 2nd trip

我想计算每个“用户id”的行程长度之和并保存在字典中。旅行应该从“开始”开始,在“结束”结束。例如,这里我们应该有这样的结果:

myDict={(1: 14), (2: 22),...}

按键显示第i次行程,数值显示行程长度

有人能帮我吗


Tags: 数据inidforherestatusstartend
1条回答
网友
1楼 · 发布于 2024-10-03 09:11:47

可能有一个更聪明的解决方案,但这应该是可行的。我们需要遍历这些行

trips = {} #Initialize dict
onTrip = False 
i = 1
for index, row in dfTrip.iterrows():

    if row['status']=='start': #Start the trip
        onTrip=True
        trips[i]=row['length']
        continue

    if onTrip: #Add each value of the trip
        trips[i]+=row['length']

    if row['status']=='end': #End the trip, incrementing i
        onTrip=False
        i+=1

相关问题 更多 >