Reputation: 142
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?
Upvotes: 1
Views: 50
Reputation: 25323
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
Upvotes: 2
Reputation: 37767
You can use pandas.Series
constructor :
df[['col2','col3']] = df['col2'].apply(pd.Series)
print(df)
col1 col2 col3
0 asdf 2 1
1 xy 2 2
2 q 3 3
Upvotes: 1
Reputation: 260580
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
Upvotes: 2