How do I convert Python's Pandas data frame to a given dictionary type?

Asked 2 years ago, Updated 2 years ago, 47 views

Python's Pandas data frame contains the following data:

Enter a description of the image here

I would like to know how to convert this as follows:

x={'item1':1,'item2':1,'item4':1}
y = {'item1':1,'item3':1}

By the way, if you run it with this, the value of "0" will also be included, which is a shame.

In:dict(df.ix['x'])
Out: {'item1':1,'item2':1,'item3':0,'item4':1}

If there is not enough explanation, I will supplement it, so I would appreciate it if you could reply.
Thank you for your cooperation.

python pandas

2022-09-30 19:44

2 Answers

Filter by the ix() method.

>>import pandas as pd
>>>df=pd.DataFrame([
      [1, 1, 0, 1], [1, 0, 1, 0]
    ], index=['x', 'y', columns=['item1', 'item2', 'item3', 'item4')
>>df
   item1 item2 item3 item4
x1 10 1
y 10 10

>>dict(df.ix['x', (df.ix['x']==1)])
{'item2':1,'item1':1,'item4':1}
>>dict(df.ix['y', (df.ix['y']==1)])
{'item3':1,'item1':1}


2022-09-30 19:44

If it's written in one line, it's like this

x,y=[col[col!=0].to_dict()forcolin[df.loc[row] for row indf.index]]


2022-09-30 19:44

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.