Skip to content Skip to sidebar Skip to footer

How To Convert A Pandas Dataframe Column Using Transposing?

I have a dataframe like this : A B C D E F G H -------------------------- 0 xx s 1 d f df f 54 1 g g4 2

Solution 1:

First replace missing values in columns A-F by forward filling and then reshape by set_index with unstack:

cols = list('ABCDEF')
df[cols] = df[cols].ffill()

df = df.set_index(cols + ['G'])['H'].unstack().reset_index().rename_axis(None, 1)
print (df)
    A  B  C  D  E   F    1    3    d    f    g    k    r    s    x
0  as  t  r  a  2  ds  NaN  NaN  NaN  NaN  NaN   s4  NaN  NaN  NaN
1  ds  a  s  d  f  ds   gf   s3   43   64  NaN  NaN  NaN   se  NaN
2  xx  s  1  d  f  df  NaN  NaN  NaN   54   g4  NaN   43  NaN   r4

If order is important add reindex by unique values:

s = df['G'].unique()
df = df.set_index(cols + ['G'])['H'].unstack().reindex(columns=s).reset_index().rename_axis(None, 1)
print (df)
    A  B  C  D  E   F    f    g    x    r    d    s    1    3    k
0  as  t  r  a  2  ds  NaN  NaN  NaN  NaN  NaN  NaN  NaN  NaN   s4
1  ds  a  s  d  f  ds   64  NaN  NaN  NaN   43   se   gf   s3  NaN
2  xx  s  1  d  f  df   54   g4   r4   43  NaN  NaN  NaN  NaN  NaN

Post a Comment for "How To Convert A Pandas Dataframe Column Using Transposing?"