【问题标题】:Python pandas getting value of the dictionary in columnPython pandas在列中获取字典的值
【发布时间】:2016-02-26 12:10:19
【问题描述】:

我正在使用 pandas 创建一个数据框,一切都很好,但我有两列,其中包含字典。如何拆分此列以提取价格值和股权值。

             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}   

我对此有一个解决方案,但是当第 7 行出现 NaN 时就会出现问题。

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

你能帮帮我吗?

【问题讨论】:

  • 所以你只是想忽略NaNtable.loc[table['AgainstSidePrices'].notnull(), 'AgainstSidePrices'].apply(lambda x: x.get('_Price'))
  • 谢谢。一切都解决了。

标签: python python-2.7 python-3.x pandas


【解决方案1】:

根据您的需要,将其应用于非空条目:

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

或更改apply 函数来处理此问题:

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

请注意,答案的维度是不同的:第一个仅适用于相关行,第二个适用于所有。

【讨论】:

    猜你喜欢
    • 2022-01-05
    • 2019-05-24
    • 2013-08-22
    • 1970-01-01
    • 1970-01-01
    • 2017-10-23
    • 2020-10-13
    • 1970-01-01
    • 2017-12-27
    相关资源
    最近更新 更多