【问题标题】:Copy pandas value only to dictionary: suppress index [duplicate]仅将熊猫值复制到字典:抑制索引 [重复]
【发布时间】:2020-05-08 00:21:01
【问题描述】:

我只需要将值从 DF 复制到 dict 以用于将 dict 作为参数的显示函数。

我的数据框在以下摘录中称为databases

DB_stat_reporting = dict()
report_month = databases.loc[databases['Date'] == reporting_month]
last_year    = databases.loc[databases['Date'] == past_year]

report_month

输出:

    Date        Circ    EB  Mag     bla     drive   Total   Digi
12  2019-12-01  118324  133 1084    4928    17513   141982  23658

我只需要将值传递给字典:

DB_stat_reporting['Circ']     = report_month['Circ']
DB_stat_reporting['Circ']

生产:

12    118324

我需要对其运行一些统计信息,因此它需要保持为 int,但我不希望打印索引或括号等。

预期输出:

118324

这似乎是一件很简单的事情,但我无法做到这一点。

【问题讨论】:

标签: python pandas


【解决方案1】:

使用DataFrame.loc 获取不带索引的值本身:

DB_stat_reporting = dict()
DB_stat_reporting['Circ'] = report_month.loc[12, 'Circ']

Series.iat:

DB_stat_reporting = dict()
DB_stat_reporting['Circ'] = report_month['Circ'].iat[0]
print(DB_stat_reporting)

{'Circ': 118324}

【讨论】:

  • KeyError: '标签 [0] 不在 [index] 中'
  • 你必须选择正确的索引,所以在你的情况下使用12,所以它会是report_month.loc[12, 'Circ']
  • Series.iat 示例使用 0 工作。为什么第一个工作需要正确的索引而第一个工作?
  • loc 是基于标签的索引,所以在这种情况下 12 是标签。 iat 基于位置。
  • 有道理。谢谢!一旦计时器用完,我会接受这个答案。
猜你喜欢
  • 1970-01-01
  • 2022-01-08
  • 2019-05-03
  • 2015-11-22
  • 2018-02-03
  • 2021-12-01
  • 2020-12-01
  • 2013-12-27
相关资源
最近更新 更多