简体   繁体   中英

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                      x r4
   3                      r 43
   4  ds  a  s  d  f  ds  f 64
   5                      d 43
   6                      s se
   7                      1 gf
   8                      3 s3
   9  as  t  r  a  2  ds  k s4

How to make it in this format :

      A   B  C  D  E  F    f   g   x   r   d   s   1   3   k
     ---------------------------------------------------------
   0  xx  s  1  d  f  df  54  g4  r4  43
   1  ds  a  s  d  f  ds  64              43  se  gf  s3
   2  as  t  r  a  2  ds                                   s4

There will be more values in first dataframe.

First replace missing values in columns AF 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

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