【问题标题】:Why does this cell of a dataframe contain not a value, but a series?为什么数据框的这个单元格不包含一个值,而是一个系列?
【发布时间】:2019-02-08 16:51:52
【问题描述】:

我在 CSV 中读取到 python 中的数据框。我有一个 DateTimeIndex 和两个我感兴趣的列,我们称它们为 number 和 upper_limit。我按索引排序,删除属于旧时间戳的不必要的列和行。然后我用

计算这两列的最小值、最大值和平均值
numbercol = pd.to_numeric(df.iloc[:,0], errors='coerce')
upperlimitcol = pd.to_numeric(df.iloc[:,1], errors = 'coerce')

这很好用。现在我想用

检查数字大于upper_limit的频率
for dt in df.index:
     if numbercol[dt] >= upperlimitcol[dt]:
         overshoots += 1

但我得到了一个

ValueError: The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all().

我添加了一个打印语句来查看每个dt 的数字和上限列的值,结果发现在 1800 行之后,单元格中的值不再是数字,但是看起来像这样(这个是它给我的print(numbercol[dt]))

DateTime
2017-01-14       NaN
2017-01-14    3018.0
Name: Number, dtype: float64

numbercol[dt] 的类型也从 <type 'numpy.float64'> 更改为 <class 'pandas.core.series.Series'>

我在文本编辑器以及 Libre Office 和 Excel 中检查了该文件,但看不出这行与之前的行有任何区别。你知道为什么会这样吗?

【问题讨论】:

  • numbercol[dt] 正在返回一个系列,因为您有两条具有相同 dt 的记录。
  • upperlimitcol[dt] 返回什么?该数据帧中的时间戳是唯一的吗?

标签: python pandas dataframe series


【解决方案1】:

它正在返回一个系列,因为您有两个具有相同 dt 的记录。不知道你的问题的背景,很难说如何进行。

一种方法是使用sum()或其他一些聚合函数(即max()min()等)在for循环中聚合数据:

for dt in df.index:
   if numbercol[dt].sum() >= upperlimitcol[dt]:
       overshoots += 1

另一个可能是在你的 for 循环之前 dropna()。

numbercol = numbercol.dropna()

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-04-15
    • 2020-10-13
    • 2019-08-18
    • 1970-01-01
    • 2013-02-07
    • 2021-05-23
    相关资源
    最近更新 更多