python - Pandas 删除列包含 * 的行

标签 python pandas

我试图从此 df 中删除所有行,其中“DB Serial”列包含字符 *:

    DB Serial
0     13058
1     13069
2    *13070
3     13070
4     13044
5     13042

我正在使用:

df = df[~df['DB Serial'].str.contains('*')]

但是我得到这个错误:

    raise error, v # invalid expression
error: nothing to repeat

最佳答案

\ 转义 * 因为 * 被解释为 regex :

'*' Causes the resulting RE to match 0 or more repetitions of the preceding RE

df = df[~df['DB Serial'].str.contains('\*')]
print (df)
  DB Serial
0     13058
1     13069
3     13070
4     13044
5     13042

如果还得到:

TypeError: bad operand type for unary ~: 'float'

然后将列转换为 string,因为混合值 - 数字与字符串:

df = df[~df['DB Serial'].astype(str).str.contains('\*')]
print (df)
  DB Serial
0     13058
1     13069
3     13070
4     13044
5     13042

如果可能 NaN 的值:

df = df[~df['DB Serial'].str.contains('\*', na=False)]

关于python - Pandas 删除列包含 * 的行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43568760/

相关文章:

python - 如何从函数内定义的信号处理函数返回控制权?

python - 使用 networkx 在图中查找基数为 k 的所有 node_cut

python - Django动态页面功能和url

python dataframe 到具有多列键和值的字典

Python:__setattr__ 作为类方法//self.__dict__ 对元类的赋值

python - 导入错误: No module named requests while running spark

python - Pandas :使用 if-else 填充新列

python - Pandas 群体内的平均距离

python - 使用对新/旧索引的容差在 Pandas 中重新索引数据框

python - 无法将值转换为轴单位' - 在为 df 创建绘图时