0

I have Dataframe contain locations by string and I want to explode using them

For example, df:

country location value
Canda USA,Costa Rica, 3
Italy Germany,France,Spain 2
Russia Israel, 1

my df :

country location value
Canda USA 3
Canda Costa Rica 3
Italy Germany 2
Italy France 2
Italy Spain 2
Russia Israel 1

I have a lot more then only one column such as value and I want to make sure they are all duplicated

Henry Ecker
  • 34,399
  • 18
  • 41
  • 57

1 Answers1

1

Split and explode

df['location'] = df.location.str.rstrip(',').str.split(',')
df.explode('location')

Output

  country    location  value
0   Canda         USA      3
0   Canda  Costa Rica      3
1   Italy     Germany      2
1   Italy      France      2
1   Italy       Spain      2
2  Russia      Israel      1
Vishnudev Krishnadas
  • 10,679
  • 2
  • 23
  • 55