python-3.x - 为什么 pandas.where() 返回 'None'

标签 python-3.x pandas

我试图使用 pandas.where() 从数据框中的列中删除负值。

删除负值的最明显方法是简单地在列上运行 pandas.abs() 。所以:

import pandas as pd

frame = pd.DataFrame([-1,-1,-3,-4,-5],columns=["amount"])

frame.amount = frame.amount.abs()

但我想使用 pandas.where() 尝试同样的事情。所以我尝试了以下方法:

frame.amount = frame["amount"].where(frame["amount"] < 0, frame["amount"].abs(), inplace=True)

返回结果:

Python 3.6.1 (default, Dec 2015, 13:05:11)
[GCC 4.8.2] on linux
  amount
0   None
1   None
2   None
3   None
4   None

有两件事让我困惑:

  • 令我惊讶的是,我必须分配每个表达式 (frame.amount = ...),因为我认为在任何一种情况下调用该操作都会改变 Dataframe(这不是“就地”应该做的事情吗?)和 <
  • 为什么 pandas.where() 返回“None”

最佳答案

尝试:

frame["amount"].where(~(frame["amount"] < 0), frame["amount"].abs(), inplace=True)
#frame["amount"].mask(frame["amount"] < 0, frame["amount"].abs(), inplace=True)
print(frame)

series.where()说:

Where cond is True, keep the original value. Where False, replace with corresponding value from other.

因此,赋值的条件必须为假。 类似的是series.mask()其中说:

Replace values where the condition is True.

所以我们也可以使用相同的。

关于inplace=True,当您使用它时,不需要将结果分配回,因为inplace=True会进行就地操作,如下所示最好不要使用 inplace 并将结果分配回来。 inplace=True 返回 None,如果您分配回该系列,您将留下 None

关于python-3.x - 为什么 pandas.where() 返回 'None',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56327522/

相关文章:

python - 使用 OR 根据两列过滤数据框

mysql - 使用 to_sql 时如何防止使用第一行 Pandas DataFrame 作为列名

python-3.x - 类型错误 : 'NoneType' - Selection Sort on Python

python-3.x - Pandas Dataframe 使用合并过滤结果。编码解码问题

mysql - python执行sql请求时一直报错

python - 如何让我的模型遵循 DRY 原则

python - 有没有更好的方法来收集 pandas 中的唯一索引值?

python - Pandas :将多列分组在一个标题下

python - 使用python删除矩阵中的相应行/列

python - 如何在Python中比较两个不同.csv文件中的列?