gpt4 book ai didi

python - 按混合数据类型过滤 DataFrame

转载 作者:太空宇宙 更新时间:2023-11-04 09:34:42 25 4
gpt4 key购买 nike

我有下表,我想删除所有在其 col1 值中包含“C”的行。

     col1  col2
0 1 3
1 2 4
2 C345 3
3 A56665 4
4 34553 3
5 353535 4

下面的代码似乎只考虑 col1 值为 str 的行。为什么会这样?

import pandas as pd

d = {'col1': [1, 2, "C345", "A56665", 34553, 353535], 'col2': [3, 4,3, 4,3, 4]}
df = pd.DataFrame(data=d)
df.col1.astype(str)
print(df.dtypes)

print(df.loc[df.col1.str.contains("C") == False])

结果

     col1  col2
3 A56665 4

期望的结果:

     col1  col2
0 1 3
1 2 4
3 A56665 4
4 34553 3
5 353535 4

我使用 Python 3.6 和 pandas 0.23.4,numpy 1.15.4

最佳答案

如果检查 str.contains 的输出得到数值的缺失值:

print(df.col1.str.contains("C"))
0 NaN
1 NaN
2 True
3 False
4 NaN
5 NaN
Name: col1, dtype: object

解决方案是使用参数 nastr.contains并通过 ~ 反转 bool 掩码:

print(df[~df.col1.str.contains("C", na=False)])
col1 col2
0 1 3
1 2 4
3 A56665 4
4 34553 3
5 353535 4

详细信息:

print(df.col1.str.contains("C", na=False))
0 False
1 False
2 True
3 False
4 False
5 False
Name: col1, dtype: bool

print(~df.col1.str.contains("C", na=False))
0 True
1 True
2 False
3 True
4 True
5 True
Name: col1, dtype: bool

关于python - 按混合数据类型过滤 DataFrame,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54237394/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com