Python Dataframe Exploded List Column Into Multiple Rows
I have a dataframe like this: desc id info [a,b,c] 2 type [u,v,w] 18 tail Three columns: desc,id,info and desc is a list.I want thi
Solution 1:
Here is one way
df.set_index(['id', 'info']).desc.apply(pd.Series).stack()\
.reset_index(name = 'desc').drop('level_2', axis = 1)
id info desc
0 2 type a
1 2 type b
2 2 type c
3 18 tail u
4 18 tail v
5 18 tail w
Solution 2:
I remenber this should be from piRSquared or cᴏʟᴅsᴘᴇᴇᴅ, but can not find the link ...
idx = np.arange(len(df)).repeat(df.desc.str.len(), 0)
out = df.iloc[idx, ].assign(desc=np.concatenate(df.desc.values))
out
Out[100]:
desc id info
0 a 2 type
0 b 2 type
0 c 2 type
1 u 18 tail
1 v 18 tail
1 w 18 tail
Solution 3:
You can flatten the desc
column, repeat
the other two columns and then concatenate them:
pd.concat([
pd.Series([e for s in df.desc for e in s], name='desc'),
df.drop('desc', 1).apply(lambda col: col.repeat(df.desc.str.len())).reset_index(drop=True)
], axis=1)
#desc id info#0 a 2 type#1 b 2 type#2 c 2 type#3 u 18 tail#4 v 18 tail#5 w 18 tail
Solution 4:
You could
In [1631]: (df.loc[df.index.repeat(df.desc.str.len())]
.assign(desc=[v for x in df.desc.values for v in x]))
Out[1631]:
desc id info
0 a 2 type
0 b 2 type
0 c 2 type
1 u 18 tail
1 v 18 tail
1 w 18 tail
Post a Comment for "Python Dataframe Exploded List Column Into Multiple Rows"