Banke Singhal
Banke Singhal

Reputation: 1

Splitting Pandas column into multiple columns without using str.split()

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_$   $

Upvotes: 0

Views: 228

Answers (3)

RavinderSingh13
RavinderSingh13

Reputation: 133528

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_$   $

Upvotes: 1

anky
anky

Reputation: 75080

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_$        $

Upvotes: 2

Mohit Motwani
Mohit Motwani

Reputation: 4792

If you only want the last character you can just use:

df['Currency'] = df.Salary.str[-1]

Upvotes: 1

Related Questions