我有一个python数据框,其中包含3列:
['date', 'country', 'dollar']
country是一个字符串,通常看起来像'新加坡''乌克兰'等
有时,国家/地区列的项目是国家/地区列表,以|分隔,例如
'US|UK|Germany'
相应的行将是:
20140101, 'US|UK|Germany', 123456
我想要的是"解压缩"国家/地区列,并且每行严格限制为1个国家/地区,上面的行应该解压缩为3行:
20140101, 'US', 123456
20140101, 'UK', 123456
20140101, 'Germany', 123456
这有什么好办法吗?
谢谢!
此解决方案将更改您的列的顺序,我认为在大多数情况下这是正常的.您可以替换dict使用OrderedDict,如果你想保留列订单.
In [31]:
print DF
       date        country  dollar
0  20140101  US|UK|Germany  123456
1  20140101  US|UK|Germany  123457
[2 rows x 3 columns]
In [32]:
DF.country=DF.country.apply(lambda x: x.split('|'))
print DF
       date            country  dollar
0  20140101  [US, UK, Germany]  123456
1  20140101  [US, UK, Germany]  123457
[2 rows x 3 columns]
In [33]:
print pd.concat([pd.DataFrame(dict(zip(DF.columns,DF.ix[i]))) for i in range(len(DF))])
   country      date  dollar
0       US  20140101  123456
1       UK  20140101  123456
2  Germany  20140101  123456
0       US  20140101  123457
1       UK  20140101  123457
2  Germany  20140101  123457
[6 rows x 3 columns]
干得好:
a = [20140101, 'US|UK|Germany', 123456]
[[a[0], country, a[2]] for country in a[1].split('|')]
[[20140101, 'US', 123456],
 [20140101, 'UK', 123456],
 [20140101, 'Germany', 123456]]