gpt4 book ai didi

python - 如何在Python中过滤掉具有特定字符串的多列

转载 作者:行者123 更新时间:2023-12-01 06:56:23 26 4
gpt4 key购买 nike

我是Python新手,尤其是Pandas新手,所以我真的不知道我在做什么。我有 10 列、100000 行和 4 个字母字符串。我需要过滤掉所有列/行中不包含“DDD”的行。

我尝试使用 iloc 和 loc 来做到这一点,但它不起作用:

import pandas as pd
df = pd.read_csv("data_3.csv", delimiter = '!')
df.iloc[:,10:20].str.contains('DDD', regex= False, na = False)
df.head()

它返回一个错误:“DataFrame”对象没有属性“str”

最佳答案

我建议不要使用 for 循环,如下所示:

df[df.apply(lambda x: x.str.contains('DDD')).all(axis=1)]

仅选择字符串列

df[df.select_dtypes(include='object').apply(lambda x: x.str.contains('DDD')).all(axis=1)]

仅选择一些字符串列

selected_cols = ['A','B']
df[df[selected_cols].apply(lambda x: x.str.contains('DDD')).all(axis=1)]

关于python - 如何在Python中过滤掉具有特定字符串的多列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58790897/

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