我试图使用 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)
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/