Lynn
Lynn

Reputation: 4398

Create two new columns when splitting words with hyphen in Python

I have a dataset, df, that has a column that contains two words split by a hyphen. I would like to create two new columns with each split value.

 Value                    Type

 ABC-California           Low 
 DEF-New York             Low

Desired output:

Value1     Value2        Type

ABC        California    Low
DEF        New York      Low

What I am doing:

df.replace('-', ' ').split(' ')
df['Value1'] = df.replace('-', ' ').split(' ')

However, I am not sure how to create the new columns. Any help is appreciated.

Upvotes: 1

Views: 2139

Answers (2)

Ghilas BELHADJ
Ghilas BELHADJ

Reputation: 14106

A one line solution:

df[['Value1', 'Value2']] = df['Value'].str.split('-', 1, expand=True)

Upvotes: 3

Andrej Kesely
Andrej Kesely

Reputation: 195468

df = pd.concat([df['Value'].str.split('-', expand=True), df['Type']], axis=1)
df = df.rename(columns={0:'Value1', 1:'Value2'})
print(df)

Prints:

  Value1      Value2 Type
0    ABC  California  Low
1    DEF    New York  Low

Upvotes: 2

Related Questions