【问题标题】:Merge two 1-Column Dataframes and alternately merge elements合并两个 1 列数据框并交替合并元素
【发布时间】: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  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


【解决方案1】:

独立于仅采用唯一键的dict 的性质,您提出的方法无论如何都会在您执行groupby 时按键显式分组值。你应该改用data.set_index('Food')['Cal'].to_dict()。无论如何,正如@Cimbali 所指出的,json 键应该是唯一的。这实际上是您尝试直接转换为 json 时得到的结果:

>>> data.set_index('Food(str)')['Cal(str)'].to_json()

ValueError: Series index must be unique for orient='index'

【讨论】:

    【解决方案2】:

    到目前为止,感谢您的建议,我设法使它与此一起使用

    dict = data.to_dict(orient="records")
        my_dict = '{'
        for i in range(len(dict)):
            key = str(dict[i].values())
            my_dict += '"' + key[1:9] + '": "' + key[10:18] + '", '
        my_dict = my_dict[:len(my_dict)-2] + '}'
        my_dict = json.loads(my_dict)
    

    【讨论】:

      猜你喜欢
      • 2019-04-28
      • 1970-01-01
      • 2017-08-15
      • 2016-07-29
      • 2020-07-31
      • 2021-11-24
      • 2021-11-09
      • 2019-09-19
      相关资源
      最近更新 更多