所以我從CSV文件中的數據框大熊貓看起來像這樣:Python Pandas Dataframe:如何從數據框中的現有列表創建列?
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), ... ]
國家數對的每一行的第4列中的數字是不相同的。
我想擴大在第4列的列表中,並轉化數據框弄成這個樣子:
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
...
我的想法是,產生2個獨立的列,然後將它們加入到原始數據幀。也許事情是這樣的:
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)
上面的代碼是絕對不工作(我只希望它可以幫助表達我的想法),我不知道如何擴大日期列也是如此。
任何幫助或建議非常感謝。
非常感謝您!我會嘗試這種方式,看看它是否有效。 –
你是對的 - 第四列不是一個實際的列表,而是一個字符串,你的方法確實可以解決日期問題。謝謝! –