【问题标题】:Selecting rows where column is not null and equal to a (string) value选择列不为空且等于(字符串)值的行
【发布时间】:2021-12-30 17:55:47
【问题描述】:

所以基本上我想选择 Col A 等于字符串“嘿”的所有行。 我的问题是 Col A 可以包含 null/nan,因此我得到一个

TypeError: invalid type comparison. 

执行时:

df.loc[df['A'] == 'hey']

然后我又提出了一个条件:

df.loc[df['A'].notnull() & (df['A'] == 'hey')] 

在这里我得到同样的错误。

我做了一个 hack,我将 Col A 中的所有空值都更改为 '' 但这并不漂亮 无论如何,最好先选择 Col A 不为空的所有行,然后从那里选择所有为空的行等于“嘿”?

【问题讨论】:

  • df.loc[df['A'] .astype(str) == 'hey'] 正在工作。谢谢耶斯瑞尔

标签: python pandas dataframe selection pandas-loc


【解决方案1】:

我猜应该有一些数字,所以尝试将值转换为strings 或比较 numpy 数组:

newDf = df[df.A.astype(str) == 'hey']

或者:

newDf = df[df.A.values == 'hey']

【讨论】:

  • 嘿伙计!感谢转换为 .astype(str) 对我有用!
【解决方案2】:

这个怎么样?

df['A'] = df['A'].astype(str)
newDf = df[df.A == 'hey']

这应该会给您一个新的数据框,其中所有行都包含 A 列中的“嘿”?

【讨论】:

  • 否,因为您无法比较字符串和空值。这就是为什么我的第一个解决方案不起作用的原因。
【解决方案3】:

对于 null / NaN 值,您的逻辑很好。下面是一个例子。您应该提供一个最小且可验证的示例,指明 Python / Pandas 的版本号。

df = pd.DataFrame({'col': [np.nan, None, 'hey', 45.4352, 'somestring']})

print(df.loc[df['col'] == 'hey'])

   col
2  hey

【讨论】:

    猜你喜欢
    • 2019-11-03
    • 1970-01-01
    • 2014-07-28
    • 2017-11-04
    • 1970-01-01
    • 1970-01-01
    • 2014-01-24
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多