Arthur Zangiev
Arthur Zangiev

Reputation: 1526

Python pandas getting value of the dictionary in column

I am using pandas to create a dataframe and it is all fine, but i have two columns, which have dictionaries in it. How to split this columns to extract price value and stake value.

             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}   

I have a solution for this, but the problem appears when there is NaN like line 7.

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

Can you help me please?

Upvotes: 0

Views: 62

Answers (1)

Ami Tavory
Ami Tavory

Reputation: 76346

Depending on what you need, either apply it to the non-null entries:

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

or change the apply function to handle this:

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

Note that the dimensions of the answers are different: the first applies it only to the relevant rows, the second to all.

Upvotes: 1

Related Questions