Ricky
Ricky

Reputation: 187

How to split a column by pandas?

I have a column like that, and I want to split it by'-' into two columns, Is there any pandas method to do that? I know I could copy the column and use a regex to do that, I wonder whether there is another way. Thanks:)

             Col_A
    0      18K-22K
    1        6K-9K
    2      10K-16K
    3      15K-25K
    4        5K-7K

target:

        Col_A1 Col_A2
    0      18K    22K
    1       6K     9K
    2      10K    16K
    3      15K    25K
    4       5K     7K

Upvotes: 1

Views: 83

Answers (1)

jezrael
jezrael

Reputation: 862481

Use str.split:

df1 = df['Col_A'].str.split('-', expand=True)
df1.columns = ['Col_A1', 'Col_A2']
print (df1)
  Col_A1 Col_A2
0    18K    22K
1     6K     9K
2    10K    16K
3    15K    25K
4     5K     7K

If you want add columns to original df:

df[['Col_A1', 'Col_A2']] = df['Col_A'].str.split('-', expand=True)
print (df)
     Col_A Col_A1 Col_A2
0  18K-22K    18K    22K
1    6K-9K     6K     9K
2  10K-16K    10K    16K
3  15K-25K    15K    25K
4    5K-7K     5K     7K

Upvotes: 4

Related Questions