【问题标题】:append dictionary to data frame将字典附加到数据框
【发布时间】:2019-01-17 09:07:00
【问题描述】:

我有一个函数,它返回一个像这样的字典:

{'truth': 185.179993, 'day1': 197.22307753038834, 'day2': 197.26118010160317, 'day3': 197.19846975345905, 'day4': 197.1490578795196, 'day5': 197.37179265011116}

我正在尝试将此字典附加到这样的数据框:

output = pd.DataFrame()
output.append(dictionary, ignore_index=True)
print(output.head())

不幸的是,数据帧的打印会导致一个空的数据帧。有什么想法吗?

【问题讨论】:

  • 为什么要创建并清空要附加的数据框?你有什么理由不能只使用 pd.DataFrame.from_dict(dictionary) ?
  • @GeorgeLPerkins 我知道,但我最终必须附加几个字典。

标签: python python-3.x pandas dataframe


【解决方案1】:

您没有将值分配给结果。

output = pd.DataFrame()
output = output.append(dictionary, ignore_index=True)
print(output.head())

【讨论】:

  • output = output.append(dictionary, ignore_index=True) 与众不同...
  • 哦。我希望字典追加能够像列表追加一样工作,但事实并非如此。
  • 哦,伙计,你是救命稻草,我已经摔了一个星期了。我将它与 js 对象进行比较,看起来追加没有更新数据框
【解决方案2】:

之前的回答(用户 alex,2018 年 8 月 9 日 20:09 回答)现在会触发警告,指出在未来版本中将弃用附加到数据帧。

一种方法是将字典转换为数据框并连接数据框:

output = pd.DataFrame()
df_dictionary = pd.DataFrame([dictionary])
output = pd.concat([output, df_dictionary], ignore_index=True)
print(output.head())

【讨论】:

    猜你喜欢
    • 2023-02-25
    • 1970-01-01
    • 2022-01-06
    • 2015-10-20
    • 2021-11-07
    • 2016-06-11
    • 2017-10-12
    • 2020-09-23
    • 2023-02-24
    相关资源
    最近更新 更多