user2991421
user2991421

Reputation: 417

Extracting an element from list embedded in column

I have the following dataframe:

col1   col2
[12, 2]  4
[2, 5]  3

I want this:

col1A   col1B   col2
12        2       4
2        5       3

This question is similar to this but on doing df['col1'].str[0], I'm getting this as output:

col1   col2
[       4
[       3

Upvotes: 0

Views: 86

Answers (2)

BENY
BENY

Reputation: 323326

I will do

df=pd.DataFrame(df.pop('col1').tolist(),index=df.index).join(df)
Out[41]: 
    0   1  col2
0   1   2     1
1  10  11     2

Upvotes: 1

ansev
ansev

Reputation: 30930

Use:

new_df=df.T.apply(lambda x: x.explode()).T
print(new_df)
  col1 col1 col2
0   12    2    4
1    2    5    3

If you want rename the column use:

df2=df.T.apply(lambda x: x.explode())
groups=df2.groupby(level=0)
letters=groups.cumcount().map({0:'A',1:'B'})
df2.index=(df2.index+letters).where(groups.size()>1,df2.index.to_series())
new_df=df2.T
print(new_df)

  col1A col1B col2
0    12     2    4
1     2     5    3

Upvotes: 2

Related Questions