当我检查这个 pandas dataframe.ne
方法时,文档说它是一个用于灵活比较的包装器。我在 pandas 文档中找不到任何关于此的适当示例。为什么我们使用这个 df.ne
以及它如何使数据操作变得更容易或更灵活?是否可以给我一个使用 df.ne
和不使用 df.ne
的相同方法的示例,这将有助于我理解?
最佳答案
检查 source用于 DataFrame.ne
的实现。代码并不难理解。
本质上,DataFrame.ne
提供了一种更灵活的方式来执行不等式比较。您还可以指定其他参数,这在使用 !=
运算符时是不可能的。
例子:
DataFrame.ne
允许比较索引不对齐的两个数据帧df0 = pd.DataFrame({'a': [1,2,3], 'b': [0.1, 0.3, 0.9], 'c': [2,4,6]}, index=list('abc')) df1 = pd.DataFrame({'a': [3,2,1], 'b': [0.9, 0.3, 0.1], 'c': [6,4,2]}, index=list('cba')) df0.ne(df1) # outputs: a b c a False False False b False False False c False False False
但是
df0 != df1
引发了以下错误:ValueError: Can only compare identically-labeled DataFrame objects
DataFrame.ne
接受一个系列和参数axis
和level
。s1 = pd.Series([1,2,3], index=list('abc')) df0.ne(s1, axis=0) a b c a False True True b False True True c False True True df0.ne(s1, axis=1) a b c a False True True b True True True c True True True
后者也可以通过
df0 != s1
获取,但前者不行DataFrame.ne
也接受标量作为参数df0.ne(1) # outputs a dataframe where all values are true a b c a False True True b True True True c True True True
关于python - 什么是 pandas dataframe.ne 方法以及为什么使用它?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51338087/