gpt4 book ai didi

python - 删除/删除 pandas DataFrame 中任意列中具有特定字符串的行

转载 作者:行者123 更新时间:2023-12-01 08:51:50 29 4
gpt4 key购买 nike

可能是一个简单的答案,所以提前道歉(最少的编码经验)。

我正在尝试从任何列中删除具有特定字符串(经济 7)的任何行,并且一直在尝试离开此线程:

How to drop rows from pandas data frame that contains a particular string in a particular column?

无法让它工作,但在以前的 DataFrame(现在 df = energy)上尝试了此代码,它似乎可以工作,尽管现在出现错误:

no_eco = energy[~energy.apply(lambda series: series.str.contains('Economy 7')).any(axis=1)]

AttributeError: ('只能使用带有字符串值的 .str 访问器,该访问器在 pandas 中使用 np.object_ dtype', '发生在索引现有ProductCodeGas')

有什么建议吗? ps DataFrame 非常大。

谢谢

最佳答案

您只能选择对象列,显然是 select_dtypes 的字符串:

df = energy.select_dtypes(object)
#added regex=False for improve performance like mentioned @jpp, thank you
mask = ~df.apply(lambda series: series.str.contains('Economy 7', regex=False)).any(axis=1)
no_eco = energy[mask]

示例:

energy = pd.DataFrame({
'A':list('abcdef'),
'B':[4,5,4,5,5,4],
'C':[7,8,9,4,2,3],
'D':[1,3,5,7,1,0],
'E':[5,3,6,9,2,4],
'F':list('adabbb')
})

print (energy)
A B C D E F
0 a 4 7 1 5 a
1 b 5 8 3 3 d
2 c 4 9 5 6 a
3 d 5 4 7 9 b
4 e 5 2 1 2 b
5 f 4 3 0 4 b

df = energy.select_dtypes(object)
mask = ~df.apply(lambda series: series.str.contains('d')).any(axis=1)
no_eco = energy[mask]
print (no_eco)

A B C D E F
0 a 4 7 1 5 a
2 c 4 9 5 6 a
4 e 5 2 1 2 b
5 f 4 3 0 4 b

关于python - 删除/删除 pandas DataFrame 中任意列中具有特定字符串的行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53063557/

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