数据框分组依据-值列表

时间:2019-04-24 07:24:35

标签: python pandas pandas-groupby

我有以下数据框:

driver_id                           status  dttm
9f8f9bf3ee8f4874873288c246bd2d05    free    2018-02-04 00:19
9f8f9bf3ee8f4874873288c246bd2d05    busy    2018-02-04 01:03
8f174ffd446c456eaf3cca0915d0368d    free    2018-02-03 15:43
8f174ffd446c456eaf3cca0915d0368d    enroute 2018-02-03 17:02

3列:driver_id,状态,dttm

我需要做的是按驱动程序ID分组,并将所有状态及其各自的dttm值列出到名为'driver_info'的新列中:

driver_id                           driver_info
9f8f9bf3ee8f4874873288c246bd2d05    [("free", 2018-02-04 00:19), ("busy", 2018-02-04 01:03)]
8f174ffd446c456eaf3cca0915d0368d    [("free", 2018-02-03 15:43), ("enroute", 2018-02-03 17:02) ...]

如何在python 3中做到这一点?

我尝试了

dfg = df.groupby("driver_id").apply(lambda x: pd.concat((x["status"], x["dttm"])))

但结果与我预期的不同...

2 个答案:

答案 0 :(得分:2)

尝试:使用zip并应用(列表)

df['driver_info'] = list(zip(df['status'], df['dttm']))
df = df.groupby('driver_id')['driver_info'].apply(list)

答案 1 :(得分:2)

GroupBy.applylistzip一起用于元组列表:

df1 = (df.groupby('driver_id')
         .apply(lambda x: list(zip(x['status'], x['dttm'])))
         .reset_index(name='driver_info'))
print (df1)
                          driver_id  \
0  8f174ffd446c456eaf3cca0915d0368d   
1  9f8f9bf3ee8f4874873288c246bd2d05   

                                         driver_info  
0  [(free, 2018-02-03 15:43), (enroute, 2018-02-0...  
1  [(free, 2018-02-04 00:19), (busy, 2018-02-04 0...