简体   繁体   中英

How to unpack a list of tuple in various length in a panda dataframe?

ID LIST_OF_TUPLE (2col)
1   [('2012','12'), ('2012','33'), ('2014', '82')]
2   NA
3   [('2012','12')]
4   [('2012','12'), ('2012','33'), ('2014', '82'), ('2022', '67')]

Result:

ID TUP_1 TUP_2(3col)
1  2012   12
1  2012   33
1  2014   82
3  2012   12
4  2012   12
4  2012   33
4  2014   82
4  2022   67

Thanks in advance.

This is explode then create a dataframe and then join :

s = df['LIST_OF_TUPLE'].explode()
out = (df[['ID']].join(pd.DataFrame(s.tolist(),index=s.index)
        .add_prefix("TUP_")).reset_index(drop=True)) #you can chain a dropna if reqd

print(out)

   ID TUP_0 TUP_1
0   1  2012    12
1   1  2012    33
2   1  2014    82
3   2   NaN  None
4   3  2012    12
5   4  2012    12
6   4  2012    33
7   4  2014    82
8   4  2022    67

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