在python pandas中,如何解压缩列中的列表?

时间:2014-04-07 14:27:38

标签: python pandas

我有一个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

有什么好办法吗?

谢谢!

2 个答案:

答案 0 :(得分:5)

此解决方案将更改列的顺序,我认为在大多数情况下都可以。如果要保留列顺序,可以将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]

答案 1 :(得分:1)

你走了:

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]]