Reputation: 47
Say I use pandas to read in datatable.csv, and the table looks like this:
How could we split Column 3 such that datatable subsequently looks like this:
I've read plenty of answers to similar questions and tried using the likes of .str.rpartition('-')
, .split('-')
and .apply()
combinations, but I haven't managed to extract the separated values into columns.
Upvotes: 2
Views: 115
Reputation: 421
You can use this
df['col3']= ['1-d-w','s-3-q']
df
Out[4]:
col
0 1-d-w
1 s-3-q
df['col4']= df['col3'].apply((lambda x: x.split('-'))).apply((lambda x:x[0]))
df['col5']= df['col3'].apply((lambda x: x.split('-'))).apply((lambda x:x[1]))
df['col6']= df['col3'].apply((lambda x: x.split('-'))).apply((lambda x:x[2]))
df
Out[33]:
col3 col4 col5 col6
0 1-d-w 1 d w
1 s-3-q s 3 q
Upvotes: 0
Reputation: 153500
Use split
with expand=True
:
df[['Column 3','Column 4','Column 5']] = df['Column 3'].str.split('-', expand=True)
Example
df = pd.DataFrame({'Column 3':['X-X-0','1-0-X','X-Y-X','X-0-0','1-X-Y']})
df[['Column 3','Column 4','Column 5']] = df['Column 3'].str.split('-', expand=True)
Output:
Column 3 Column 4 Column 5
0 X X 0
1 1 0 X
2 X Y X
3 X 0 0
4 1 X Y
Upvotes: 2