Python's Pandas data frame contains the following data:
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.
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}
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]]
© 2024 OneMinuteCode. All rights reserved.