I want to expand the list in DataFrame cells in the column direction

Asked 2 years ago, Updated 2 years ago, 252 views

Now we have DataFrame listed in each of the following cells:

import pandas as pd
df = pd.DataFrame(
    {'x':[['Li', 'C', ['Li', 'N', ['Li', 'O']},},
    index=[1,2,3])

I would like to process this DataFrame as follows.

x1,2                    
'Li', 'C'
'Li', 'N'
'Li', 'O'
df_split=df.apply(pd.Series)
df_split=df.apply(lambdax:pd.Series(x['elements']).unstack().reset_index(1),axis=1)

I tried , but it didn't work.

python python3 pandas

2022-09-30 22:03

1 Answers

dfx=df['x'].apply(pd.Series).set_axis(['x1','x2',axis=1)
print(dfx)

#
   x1 x2
1Lic
2 LiN
3 LiO


2022-09-30 22:03

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.