So I have a pandas dataframe from csv file looks like this:
year,month,day,list
2017,09,01,"[('United States of America', 12345), (u'Germany', 54321), (u'Switzerland', 13524), (u'Netherlands', 24135), ... ]
2017,09,02,"[('United States of America', 6789), (u'Germany', 9876), (u'Switzerland', 6879), (u'Netherlands', 7968), ... ]
The number of country-count pairs in the 4th column of each row is not identical.
I want to expand the list in the 4th column, and transform the dataframe into something like this:
year,month,day,country,count
2017,09,01,'United States of America',12345
2017,09,01,'Germany',54321
2017,09,01,'Switzerland',13524
2017,09,01,'Netherlands',24135
...
2017,09,02,'United States of America',6789
2017,09,02,'Germany',9876
2017,09,02,'Switzerland',6879
2017,09,02,'Netherlands',7968
...
My thought was to generate 2 independent columns, then join them to the origin dataframe. Maybe Something like this:
country = df.apply(lambda x:[x['list'][0]]).stack().reset_index(level=1, drop=True)
count = df.apply(lambda x:[x['list'][1]]).stack().reset_index(level=1, drop=True)
df.drop('list', axis=1).join(country).join(count)
The code above is definitely not working (I just hope it can help express my thought), and I have no idea how to expand the date columns as well.
Any help or suggestion is much appreciated.