Shubham Kuse
Shubham Kuse

Reputation: 135

Grouping pandas dataframe based on common key

I have a file which I have parsed as pandas DataFrame but want to collectively group by their individual element at column 3 w.r.t column 2.

        0   1    2    3     4
0    00B2   0  -67   39  1.13
1    00B2  85  -72   39  1.13
2    00B2   1  -67   86  1.13
3    00B2   2  -67   87  1.13
4    00B2   3  -67   88  1.13
5    00B2  91  -67   39  1.13
6    00B2   4  -67  246  1.13
7    00B2   5  -67   78  1.13
8    00B2   6  -67   10  1.13
9    00B2   7  -67  153  1.13
10   00B2   1  -67   38  1.13
11   00B2   8  -67  225  1.13
12   00B2   9  -67  135  1.13
13   00B2  10  -67   23  1.13
14   00B2   4  -67   38  1.13
15   00B2  11  -67  132  1.13
16   00B2  12  -71  214  1.13
17   00B2  13  -71   71  1.13
18   00B2  14  -71  215  1.13
19   00B2   8  -71   38  1.13
20   00B2  15  -71  249  1.13
21   00B2  16  -71  174  1.13
22   00B2  17  -71  196  1.13
23   00B2  18  -71   38  1.13
24   00B2  19  -71  252  1.13
25   00B2  20  -71  196  1.13
26   00B2  21  -71   39  1.13
27   00B2  22  -71   39  1.13
28   00B2  23  -71  252  1.13
29   00B2  24  -71   39  1.13
..    ...  ..  ...  ...   ...

I want the data that looks something like this

DF1:

-67     37
-72     37
-71     37
...     ...

DF2:

-68     38
-67     38
-70     38
...     ...

DF3:

-64     39
-63     39
-62     39
...     ...

I have tried the following:

e1 = pd.DataFrame(e1)
print (e1)
group = e1[3][2] == "group"
print (e1[group])

This leads to nowhere close to what I want so how to groupby such data according to my requirement?

Upvotes: 1

Views: 58

Answers (1)

jezrael
jezrael

Reputation: 862406

I think need create dictionary of Series by converting groupby object to tuples and dicts:

d = dict(tuple(df.groupby(3)[2]))

print (d[39])
0    -67
1    -72
5    -67
26   -71
27   -71
29   -71
Name: 2, dtype: int64

For DataFrame:

d1 = dict(tuple(df.groupby(3)))

print (d1[39])
       0   1   2   3     4
0   00B2   0 -67  39  1.13
1   00B2  85 -72  39  1.13
5   00B2  91 -67  39  1.13
26  00B2  21 -71  39  1.13
27  00B2  22 -71  39  1.13
29  00B2  24 -71  39  1.13

Upvotes: 1

Related Questions