python - df.to_dict() 只得到一行原始数据帧(df)

标签 python pandas dictionary

我有以下数据框:

注意:日期是索引

city    morning afternoon   evening midnight
date                    
2014-05-01  YVR 2.32    4.26    -4.87   6.58
2014-05-01  YYZ 24.78   2.90    -50.55  6.64
2014-05-01  DFW 24.78   2.90    -50.55  6.64
2014-05-01  PDX 2.40    4.06    -4.06   6.54
2014-05-01  SFO 30.35   9.96    64.24   6.66

我尝试通过 df.to_dict() 将此 df 保存到字典中,但我只得到一行:

df.to_dict():

{'city': {Timestamp('2014-05-01 00:00:00'): 'SFO'},
 'morning': {Timestamp('2014-05-01 00:00:00'): 9.9600000000000009},
 'afternoon': {Timestamp('2014-05-01 00:00:00'): 6.6600000000000001},
 'evening': {Timestamp('2014-05-01 00:00:00'): 30.350000000000001},
 'midnight': {Timestamp('2014-05-01 00:00:00'): 64.239999999999995}}

不应该在字典中输出整个数据帧吗?

最佳答案

您得到的输出是使用索引作为字典中的键。您有一个重复索引,并且字典键必须是唯一的,所以它不会起作用。

您必须选择另一种输出格式。我发现 records 很有用,如

In [65]: df.reset_index().to_dict("records")
Out[65]: 
[{'afternoon': 4.26,
  'city': 'YVR',
  'date': '2014-05-01',
  'evening': -4.87,
  'midnight': 6.58,
  'morning': '2.32'},
 {'afternoon': 2.9,
  'city': 'YYZ',
  'date': '2014-05-01',
  'evening': -50.55,
  'midnight': 6.64,
  'morning': '24.78'},
 {'afternoon': 2.9,
  'city': 'DFW',
  'date': '2014-05-01',
  'evening': -50.55,
  'midnight': 6.64,
  'morning': '24.78'},
 {'afternoon': 4.06,
  'city': 'PDX',
  'date': '2014-05-01',
  'evening': -4.06,
  'midnight': 6.54,
  'morning': '2.40'},
 {'afternoon': 9.96,
  'city': 'SFO',
  'date': '2014-05-01',
  'evening': 64.24,
  'midnight': 6.66,
  'morning': '30.35'}]

关于python - df.to_dict() 只得到一行原始数据帧(df),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38809705/

相关文章:

javascript - 为什么过滤字典上的 `ng-repeat` 会导致 `10 $digest() iterations reached` 错误?

python - 让 pip 与 git 和 github 存储库一起工作

python - 如何将任何 Google API 服务对象传递给 App Engine 中的延迟任务?

python - 如何在 Pandas 中用前一天的值填充一天的零

python - 相当于 numpy 数组的 pandas read_sql_query?

python - 按键用先前或后续值填充缺失值

python - 确定您在 python 循环中进行的迭代

python - 尝试将多个函数聚合到新列时出现意外的 KeyError Pandas

python - 在 Windows 上安装 Jinja2 时遇到问题

python - 可以 pickle 然后检索 matplotlib 图形对象吗?