2016-02-26 74 views
0

我正在使用熊猫来创建一个数据框,它都很好,但我有两列,其中有字典。如何拆分这些列以提取价格价值和股权价值。Python熊猫获得字典在列中的价值

   AgainstSidePrices      ForSidePrices 
0 {u'_Price': 4.8, u'_Stake': 160.69} {u'_Price': 4.6, u'_Stake': 21.44} 
1  {u'_Price': 4.8, u'_Stake': 5.69}  {u'_Price': 4.7, u'_Stake': 4.0} 
2  {u'_Price': 5.0, u'_Stake': 22.32} {u'_Price': 4.9, u'_Stake': 15.34} 
3  {u'_Price': 5.6, u'_Stake': 15.18} {u'_Price': 5.4, u'_Stake': 14.82} 
4  {u'_Price': 9.6, u'_Stake': 4.22} {u'_Price': 9.4, u'_Stake': 6.71} 
5  {u'_Price': 12.5, u'_Stake': 4.0} {u'_Price': 11.5, u'_Stake': 12.35} 
6  {u'_Price': 950.0, u'_Stake': 2.0} {u'_Price': 128.0, u'_Stake': 2.25} 
7         NaN         NaN 
8  {u'_Price': 4.8, u'_Stake': 4.72} {u'_Price': 4.6, u'_Stake': 9.32} 
9  {u'_Price': 4.9, u'_Stake': 2.0} {u'_Price': 4.7, u'_Stake': 3.92} 

我有一个解决方案,但是当有喜欢的NaN线出现问题7

table['price'] = table['AgainstSidePrices'].apply(lambda x: x.get('_Price')) 

你能帮助我吗?

+2

所以你只是想忽略'NaN'? 'table.loc [table ['AgainstSidePrices']。notnull(),'AgainstSidePrices']。apply(lambda x:x.get('_ Price'))' – EdChum

+0

谢谢。这一切都奏效了。 –

回答

1

根据你所需要的,无论是将其应用到非空条目:

table.AgainstSidePrices[table.AgainstSideProces.notnull()].apply(...) 

或改变apply函数来处理这个问题:

... apply(lambda x: <something> if x is None else x.get('_Price')) 

注意答案的尺寸是不同的:第一个只适用于相关的行,第二个适用于所有行。

+0

'notnull'比'〜isnull'更具可读性IMO – EdChum

+0

@EdChum非常感谢。将更新。 –