简体   繁体   English

将 python 中的 dataframe 转换为 json 或字典类型 object

[英]convert dataframe in python to json or dictionary type object

I have data frame like我有像这样的数据框

data = pd.DataFrame({'col1' :['A','A','A','B','B','C','C','C'], 'col2': ['13','15','17','11','15','12','21','23'], 'col3' : [3,5,8,7,2,5,1,3]},columns= ['col1', 'col2', 'col3'])

print(data)

  col1 col2  col3
0    A   13     3
1    A   15     5
2    A   17     8
3    B   11     7
4    B   15     2
5    C   12     5
6    C   21     1
7    C   23     3

I want to convert this dataframe into like我想把这个 dataframe 转换成 like

[{"A": {"col2": ["13": 3,"15": 5,"17": 8]},"B": {"col2": ["11": 7,"15": 2]},"C": {"col2": ["12": 5,"21": 1,"23": 3]}}]

I tried using groupby by 'col1' then converting last two columns into dictionary but it not getting desired result.我尝试通过'col1'使用groupby,然后将最后两列转换为字典,但没有得到想要的结果。

Thank you for help.谢谢你的帮助。

You'll have to bite the bullet and use a lambda with a groupby statement.您必须硬着头皮使用带有 groupby 语句的 lambda 。

Note lambda's aren't very efficient and this doesn't really seem like a logical / proper json structure.注意 lambda 的效率不是很高,这看起来不像是一个合乎逻辑/正确的 json 结构。

but to answer your question.但要回答你的问题。

data.groupby('col1')\
         .apply(lambda x : {'col2' : dict(zip(x['col2'],x['col3']))}).to_dict()


{'A': {'col2': {'13': 3, '15': 5, '17': 8}},
 'B': {'col2': {'11': 7, '15': 2}},
 'C': {'col2': {'12': 5, '21': 1, '23': 3}}}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM