【发布时间】:2021-07-07 12:29:57
【问题描述】:
目前我遇到了一个更大的问题。我有一个 2 列 1000 行的数据框:
| Food(str) | Cal(str) | |
|---|---|---|
| 1 | Apple | 0.2 |
| 2 | Apple | 0.25 |
| 3 | Strwaberry | 1.5 |
| 4 | Hamburger | 3 |
| 5 | Rice | 0.007 |
| 6 | Strawberry | 1.4 |
为了进一步计算,我需要一个非嵌套的 Json 对象,它应该如下所示:
{'Apple' : '0.2' , 'Apple' : '0.25', 'Strawberry' : '1.5', 'Hamburger' : '3', 'Rice' : '0.007', 'Strawberry' : '1.4'}
我之前尝试过通过 pd.groupby 实现这一点:
data = data.groupby('Food').sum().T.to_dict(orient="records")[0]
这是行不通的,因为它没有考虑重复的食物,因为它会将它们分组并只是总结 Cal's。不过,我需要每个数据对。
我目前尝试接收所需的解决方案是将 Df 转置为最后我只有一行 1000 列来使用 pandas .to_json 方法来获得所需的结果。
| 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | |
|---|---|---|---|---|---|---|---|---|---|---|---|---|
| Food/Cal | Apple | 0.2 | Apple | 0.25 | Strwaberry | 1.5 | Hamburger | 3 | Rice | 0.007 | Strawberry | 1.4 |
我试图得到这个 Df 是跟随但没有工作
dataFood = data['Food']
dataFood = dataFood.reset_index()
dataFood = dataFood.T
datacal = data['Cal']
datacal = datacal.reset_index()
datacal = datacal.T
a = pd.DataFrame([1], columns=['delete'])
for c1 in dataFrom:
for c2 in dataprice:
a = pd.concat([dataFood.iloc[0, c1], datacal.iloc[0, c2]])
错误:
TypeError: cannot concatenate object of type '<class 'int'>'; only Series and DataFrame objs are valid
有人知道如何解决这个问题吗?
提前感谢您的反馈!
【问题讨论】:
-
所以只是为了检查我是否正确 - 您明确希望输出 json 格式中的重复键? (请参阅this question 了解为什么不建议这样做)
-
你需要记住 JSON 就像 dicts 一样工作,即使你可以写重复的键,只有第二个会在执行时被考虑。一种可能性是获取相同键的值列表,如
{ "apple": [0.2 ,0.25] },但我认为这不是你想要的。
标签: python json pandas dataframe