简体   繁体   中英

Creating list of lists using groupby dates in pandas dataframe

df =

        Date     Slot
0   2022-02-23    34
1   2022-02-23    35
2   2022-02-24     0
3   2022-02-24     1
4   2022-02-25     0
5   2022-02-25     1

This is my df and I want a list of lists for all the 'Slot' values having the same corresponding 'Date' value ie my output should look like [[34,35] , [0,1] , [0,1]]

PS: The values in the date column are not known beforehand so hardcoding is not working out here, is there a generalized to do this task.

You can try

out = df.groupby('Date')['Slot'].agg(list).tolist()
#
out = df.groupby('Date')['Slot'].apply(list).tolist()
print(out)

[[34, 35], [0, 1], [0, 1]]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM