【问题标题】:Logical Operator Not Working Properly In Pandas逻辑运算符在 Pandas 中无法正常工作
【发布时间】:2018-08-03 20:28:48
【问题描述】:

终于在苦苦挣扎之后来到这里寻求帮助..

我有一个数据框,它是 groupby 函数的结果,看起来像这样

 >>temp.head()

     PO_Amount  PO_Amount_Mean  id     
0     3756.6          3756.6     0
1     3756.6          3756.6     1
2    11269.8         11269.8     2
3    11269.8         11269.8     3
4     3756.6          3756.6     4


temp.dtypes
Out[141]: 
PO_Amount         float64
PO_Amount_Mean    float64
id                  int32
dtype: object

如果 PO_Amount 等于 PO_Amount_Mean,我正在尝试获取数据

temp[temp['PO_Amount']==temp['PO_Amount_Mean']]
Out[142]: 
   PO_Amount  PO_Amount_Mean  id
0     3756.6          3756.6   0
1     3756.6          3756.6   1
4     3756.6          3756.6   4
6     3756.6          3756.6   6

不知道为什么要输出索引 2 和 3。请帮忙。

【问题讨论】:

  • 我假设“正在输出”实际上是相反的意思。如果 pandas 认为它​​们不相等,你应该看看区别:temp['PO_Amount'] - temp['PO_Amount_Mean'] 显示什么?
  • 无法重现此问题,我尝试时显示整个数据框
  • 这可能是浮点精度问题。 Pandas 的工作方式与预期完全一致,但您需要先将数量和均值转换为小数,或者使用 np.close 之类的东西来比较浮点列。
  • 试试看print(temp.PO_Amount[2])print(temp.PO_Amount_Mean[2])

标签: python-3.x pandas pandas-groupby logical-operators


【解决方案1】:

感谢大家的回复。这是浮点精度问题。

temp.PO_Amount_Mean[2]
Out[10]: 11269.800000000001

temp.PO_Amount[2]
Out[11]: 11269.8

【讨论】:

  • 但是除了四舍五入之外,有没有办法比较这样的浮点数?
  • 您可以使用numpy.isclose。我相信这种情况在默认容差范围内
猜你喜欢
  • 1970-01-01
  • 2015-11-27
  • 2015-04-25
  • 1970-01-01
  • 2020-08-15
  • 2019-06-09
  • 2021-02-06
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多