[英]Converting data-frame into a dictionary by having the multiple lists?
I have a dataframe –mydata- consists of 500 rows something like this:我有一个数据框 –mydata- 由 500 行组成,如下所示:
Id Name Score
R1 sam 76
R1 Sosan 8
.. … …
R4 jack 2
R4 Tom 76
R4 samy 8
R5 Check 9
… …
Now, I want to convert the dataframe into a dictionary so that the uniqe Ids become the keys and the rows of the uniques Ids become a list.现在,我想将数据框转换为字典,以便 uniqe Id 成为键,而唯一 Id 的行成为列表。 For example, considering the above example, R1 should be a key and the inside of R1 we should have two lists, or for R4 we should have three lists etc. I have treid the below code, but it ignores the unique Ids :例如,考虑上面的例子,R1 应该是一个键,在 R1 内部我们应该有两个列表,或者对于 R4 我们应该有三个列表等等。我已经编写了下面的代码,但它忽略了唯一的 Ids :
mydictest= mydata.set_index('Id').T.to_dict('list').copy()
So, my desired output should be like this:所以,我想要的输出应该是这样的:
{'R1': [['sam', 78],['Sosan',8]], 'R4': [['Jack', 2],['Tom', 76],
['samy', 8]]}
Maybe you can try something like this:也许你可以尝试这样的事情:
df = pd.DataFrame([['R1', 'sam', 78], ['R2', 'rem', 65], ['R1', 'pem', 56]], columns=['Id', 'Name', 'Score'])
d = df.set_index('Id').to_dict(orient='split')
req_dict = {}
for ind, data in zip(d['index'], d['data']):
if ind in req_dict:
req_dict[ind].append(data)
else:
req_dict[ind] = [data]
print(req_dict)
Output:输出:
{'R1': [['sam', 78], ['pem', 56]], 'R2': [['rem', 65]]}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.