Philipp Conen
Philipp Conen

Reputation: 1

Shrink a Pandas data frame by groups in a column

I tried to change this data frame:

   X_Coord  Name  MaxDisplacement
0        1  0.03               11
1        2  0.03               22
2        3  0.03               33
3        1  0.02               44
4        2  0.02               55
5        3  0.02               66
6        1  0.01               77
7        2  0.01               88
8        3  0.01               99

to something like this:

X_Coord 0.03 0.02 0.01 
0 1 11 44 77 
1 2 22 55 88 
2 3 33 66 99 

but for less trivial cases.


I then tried some preprocessing that ends with this:

X_Coord 0.03 0.02 0.01 
0 1 11 NaN NaN 
1 2 22 NaN NaN 
2 3 33 NaN NaN 
3 1 NaN 44 NaN 
4 2 NaN 55 NaN 
5 3 NaN 66 NaN 
6 1 NaN NaN 77 
7 2 NaN NaN 88 
8 3 NaN NaN 99 

Finally, I got stock with this: df_out = df_out.groupby('X_Coord').apply(lambda x: x.bfill().ffill()).reset_index(drop=True) which works for this easy case but not for more complex like this: Input:

   X_Coord  Name  MaxDisplacement
0        1  0.03               11
1        2  0.02               22
2        3  0.01               33
3        1  0.02               44
4        2  0.03               55
5        3  0.01               66
6        1  0.01               77
7        2  0.02               88
8        3  0.03               99

Output:

   X_Coord  0.03  0.02  0.01
0        1  11.0  44.0  77.0
1        2  55.0  22.0   NaN
2        3  99.0   NaN  33.0
3        2  55.0  22.0   NaN
4        1  11.0  44.0  77.0
5        2  55.0  88.0   NaN
6        3  99.0   NaN  33.0
7        3  99.0   NaN  66.0
8        1  11.0  44.0  77.0

Upvotes: 0

Views: 46

Answers (0)

Related Questions