Home > other >  How to split the pandas column into two
How to split the pandas column into two

Time:10-05

import pandas as pd
df = pd.DataFrame({'col1': ['asdf', 'xy', 'q'], 'col2': [(2, 1), (2, 2), (3, 3)]})

I have dataframe above. I wish to split the column col2 such as below:

import pandas as pd
df = pd.DataFrame({'col1': ['asdf', 'xy', 'q'], 'col2': [2, 2, 3], 'col3': [1, 2, 3]})

Is it possible?

CodePudding user response:

You can use to_list and 2D assignment:

df[['col2', 'col3']] = df['col2'].tolist()

output:

   col1  col2  col3
0  asdf     2     1
1    xy     2     2
2     q     3     3

Or, if you want to remove 'col2' and assign to another name, using pop:

df[['col3', 'col4']] = df.pop('col2').tolist()

output:

   col1  col3  col4
0  asdf     2     1
1    xy     2     2
2     q     3     3

CodePudding user response:

You can use pandas.Series constructor :

df[['col2','col3']] = df['col2'].apply(pd.Series)

# Output :

print(df)

   col1  col2  col3
0  asdf     2     1
1    xy     2     2
2     q     3     3

CodePudding user response:

Yet another possible solution:

df['col2'], df['col3'] = zip(*df.col2)

Output:

   col1  col2  col3
0  asdf     2     1
1    xy     2     2
2     q     3     3
  • Related