我想用一个或条件来过滤我的数据帧,以保持特定列的值超出范围[-0.25,0.25]的行。我尝试了:

df = df[(df['col'] < -0.25) or (df['col'] > 0.25)]

但我得到了错误:

级数的真值不明确。使用a.empty、a.bool()、a.item()、.any()或.all()


当前回答

我在熊猫数据框架中工作时也遇到过同样的问题。

我使用过:numpy.logical_and:

在这里,我试图选择Id与41d7853匹配且degree_type不与Certification匹配的行。

如下所示:

display(df_degrees.loc[np.logical_and(df_degrees['person_id'] == '41d7853' , df_degrees['degree_type'] !='Certification')])

如果我尝试编写如下代码:

display(df_degrees.loc[df_degrees['person_id'] == '41d7853' and df_degrees['degree_type'] !='Certification'])

我们将得到错误:

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

我使用了numpy.logical_,它对我很有用。

其他回答

我在熊猫数据框架中工作时也遇到过同样的问题。

我使用过:numpy.logical_and:

在这里,我试图选择Id与41d7853匹配且degree_type不与Certification匹配的行。

如下所示:

display(df_degrees.loc[np.logical_and(df_degrees['person_id'] == '41d7853' , df_degrees['degree_type'] !='Certification')])

如果我尝试编写如下代码:

display(df_degrees.loc[df_degrees['person_id'] == '41d7853' and df_degrees['degree_type'] !='Certification'])

我们将得到错误:

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

我使用了numpy.logical_,它对我很有用。

我遇到了同样的错误,并在PySpark数据帧中停滞了几天。由于我比较了两个字段中的整数值,所以通过用0填充na值,我成功地解决了这个问题。

您需要在panda中使用按位运算符|而不是或和&,而不是和。您不能简单地使用python中的bool语句。

对于非常复杂的过滤,请创建一个掩码并在数据帧上应用该掩码。将所有查询放入掩码并应用它,

mask = (df["col1"]>=df["col2"]) & (stock["col1"]<=df["col2"])
df_new = df[mask]

一件小事,浪费了我的时间。

将条件(如果使用“=”,“!=”进行比较)放在括号中。未能做到这一点也会引发这种例外。

这将起作用:

df[(some condition) conditional operator (some conditions)]

这不会:

df[some condition conditional-operator some condition]

这个出色的答案很好地解释了正在发生的事情,并提供了解决方案。我想添加另一种可能适用于类似情况的解决方案:使用查询方法:

df = df.query("(col > 0.25) or (col < -0.25)")

请参见索引和选择数据。

(我目前正在使用的数据帧的一些测试表明,这种方法比在一系列布尔运算中使用逐位运算符要慢一点:2毫秒对870µs)

一条警告:至少有一种情况是列名恰好是Python表达式,这一点并不简单。我的列名为WT_38hph_IP_2、WT_38ph_input_2和log2(WT_38kph_IP_2/WT_38lph_input_2),希望执行以下查询:“(log2(WT_38hph_IP_2/WT_38hph_input_3)>1)和(WT_38h ph_IP_2>20)”

我获得了以下异常级联:

键错误:“log2”UndefinedVariableError:未定义名称“log2”ValueError:“log2”不是受支持的函数

我想发生这种情况是因为查询解析器试图从前两列中提取一些内容,而不是用第三列的名称来标识表达式。

这里提出了一种可能的解决方法。