简体   繁体   中英

How to transpose list elements from multiple columns into rows in pandas DataFrame?

I've got a dataframe like this:

                     args  inputs
0  [a.pl, foo, -bar, baz]  [a, b]
1  [a.pl, BAH, -bar, baz]  [a, c]

There are multiple columns, and all cells contain a list of strings. How can I transpose these lists to produce this:

         args inputs
index i             
0     1  a.pl      a
      2   foo      b
      3  -bar    NaN
      4   baz    NaN
1     1  a.pl      a
      2   BAH      c
      3  -bar    NaN
      4   baz    NaN

Something like stack + unstack

df.stack().apply(pd.Series).stack().unstack(1)
Out[27]: 
     args inputs
0 0  a.pl      a
  1   foo      b
  2  -bar   None
  3   baz   None
1 0  a.pl      a
  1   BAH      c
  2  -bar   None
  3   baz   None

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