我想用一个或条件来过滤我的数据帧,以保持特定列的值超出范围[-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_,它对我很有用。

其他回答

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

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

这将起作用:

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

这不会:

df[some condition conditional-operator some condition]

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

我使用过: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值,我成功地解决了这个问题。

Pandas使用位&|。此外,每个条件都应该包装在()内。

这是有效的:

data_query = data[(data['year'] >= 2005) & (data['year'] <= 2010)]

但没有括号的相同查询不会:

data_query = data[(data['year'] >= 2005 & data['year'] <= 2010)]

我在这个命令中遇到了一个错误:

if df != '':
    pass

但当我把它改成这样时,它起了作用:

if df is not '':
    pass