How to split a DataFrame on each different value in a column?

前端 未结 3 1055
萌比男神i
萌比男神i 2021-01-23 10:16

Below is an example DataFrame.

      0      1     2     3          4
0   0.0  13.00  4.50  30.0   0.0,13.0
1   0.0  13.00  4.75  30.0   0.0,13.0
2   0.0  13.00           


        
3条回答
  •  灰色年华
    2021-01-23 11:12

    Looks like you want to groupby the first colum. You could create a dictionary from the groupby object, and have the groupby keys be the dictionary keys:

    out = dict(tuple(df.groupby(0)))
    

    Or we could also build a list from the groupby object. This becomes more useful when we only want positional indexing rather than based on the grouping key:

    out = [sub_df for _, sub_df in df.groupby(0)]
    

    We could then index the dict based on the grouping key, or the list based on the group's position:

    print(out[0])
    
        0     1     2     3         4
    0  0.0  13.0  4.50  30.0  0.0,13.0
    1  0.0  13.0  4.75  30.0  0.0,13.0
    2  0.0  13.0  5.00  30.0  0.0,13.0
    3  0.0  13.0  5.25  30.0  0.0,13.0
    4  0.0  13.0  5.50  30.0  0.0,13.0
    5  0.0  13.0  5.75   0.0  0.0,13.0
    6  0.0  13.0  6.00  30.0  0.0,13.0
    

提交回复
热议问题