我试图从此 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/