Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Storing a dictionary within a pandas dataframe cell

I am trying to record changes I make to a dataframe and I am looking for the best way to add a dictionary to a cell for later use:

Example code:

trade_information = {'Jim' : ['1','2'], 'Matt' : ['3','4']}
current_time = datetime.datetime.now(pytz.timezone('Australia/Sydney')) 
transaction_details =  pd.DataFrame({'Transaction_Number': 1 , 'Transaction_DateTime': current_time, 'Transaction_Type': 'Trade', 'Transaction_Details': trade_information }) 

transaction_details

gives me:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

enter image description here

But my desired result id:

    Transaction_Number   Transaction_DateTime       Transaction_Type    Transaction_Details
           1    2022-01-18 23:06:41.335809+11:00    Trade               {Jim:[1, 2], Matt: [3,4]}

I’m not sure if this is possible or not. The use case is that i need this information to restore transactions on the original dataframe (by accessing the dictionary within Transaction_Details).

Any help would be much appreciated! Thanks!

>Solution :

Use one elemenet list for store dict:

trade_information = {'Jim' : ['1','2'], 'Matt' : ['3','4']}
current_time = datetime.datetime.now(pytz.timezone('Australia/Sydney')) 
transaction_details =  pd.DataFrame({'Transaction_Number': 1 ,
                                     'Transaction_DateTime': current_time, 
                                     'Transaction_Type': 'Trade', 
                                     'Transaction_Details': [trade_information] }) 
print (transaction_details)
   Transaction_Number             Transaction_DateTime Transaction_Type  \
0                   1 2022-01-18 23:15:20.970362+11:00            Trade   

                       Transaction_Details  
0  {'Jim': ['1', '2'], 'Matt': ['3', '4']}  

For unpack is possible use Series.str.get:

print (transaction_details['Transaction_Details'].str.get('Jim'))
0    [1, 2]
Name: Transaction_Details, dtype: object
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading