Is there a way in Pandas to split a column into multiple columns? I have a columns in a dataframe where the contents are as follows:
Test1 Test2 Salary
1 Akash 100_$
2 Akash 200_@
3 Yogi 300_%
4 Akash 400_$
I would like to split this into:
Test1 Test2 Salary Currency
1 Akash 100_$ $
2 Akash 200_@ @
3 Yogi 300_% %
4 Akash 400_$ $
using s.str.extract
df['Currency']=df.Salary.str.extract('(\W)')
#or df['Currency']=df.Salary.str.split("_").str[1]
\\W --> Any character that is not a letter, numeric digit, or the underscore character.
print(df)
Test1 Test2 Salary Currency
0 1 Akash 100_$ $
1 2 Akash 200_@ @
2 3 Yogi 300_% %
3 4 Akash 400_$ $
如果只需要最后一个字符,则可以使用:
df['Currency'] = df.Salary.str[-1]
Without using str.split
try following.
df['Currency']=df.Salary.str.replace(".*_", "")
df
Test1 Test2 Salary Currency
0 1 Akash 100_$ $
1 2 Akash 200_@ @
2 3 Yogi 300_% %
3 4 Akash 400_$ $
OR(in case someone wants to use str.split
:
Could you please try following, using str.split here.
df['Currency']=df.Salary.str.split('_').str[1]
While printing df
output will be as follows.
Test1 Test2 Salary Currency
0 1 Akash 100_$ $
1 2 Akash 200_@ @
2 3 Yogi 300_% %
3 4 Akash 400_$ $
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.