I have a dataframe like this
Input
>>> df
sent cite
a 1,2,3
b 2,4
c 5
I want to transpose the dataframe that each row contains the values of cite and sent combined. Notice that the cite
and the sent
can be repeated (eg, cite 2
)
Expected Output
>>> df
cite sent
1 a
2 a
2 b
3 a
4 b
5 c
I have tried with this but it did not work
df = df.pivot( columns='cite', values='sent')
Use Series.str.split
with df.explode
and df.sort_values
:
In [141]: df = df.assign(cite=df['cite'].str.split(',')).explode('cite').sort_values('cite')
In [142]: df
Out[142]:
sent cite
0 a 1
0 a 2
1 b 2
0 a 3
1 b 4
2 c 5
Try split
then explode
df = df.assign(cite=df['cite'].str.split(',')).explode('cite')
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.