gpt4 book ai didi

python - 过滤列中包含特定值的行

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

我想通过数据框中的多个列过滤掉包含特定值的行。

例如

    code tag number floor  note
1 1111 * ** 34 no
2 2323 7 899 7 no
3 3677 # 900 11 no
4 9897 10 134 * no
5 # # 566 11 no
6 3677 55 908 11 no

我想过滤掉代码、标签、数字、楼层中所有包含#、*、**的行。

我想得到的是

    code tag number floor  note
1 1111 * ** 34 no
3 3677 # 900 11 no
4 9897 10 134 * no
5 # # 566 11 no

我试图在数据框中使用 isin 方法,但它确实适用于一列,但不适用于多列。谢谢!

最佳答案

选项 1
假设没有其他预先存在的 pir

df[df.replace(['#', '*', '**'], 'pir').eq('pir').any(1)]

code tag number floor note
1 1111 * ** 34 no
3 3677 # 900 11 no
4 9897 10 134 * no
5 # # 566 11 no

选项 2
讨厌的 numpy 广播。一开始速度很快,但以二次方式扩展

df[(df.values[None, :] == np.array(['*', '**', '#'])[:, None, None]).any(0).any(1)]

code tag number floor note
1 1111 * ** 34 no
3 3677 # 900 11 no
4 9897 10 134 * no
5 # # 566 11 no

选项 3
不那么讨厌 np.in1d

df[np.in1d(df.values, ['*', '**', '#']).reshape(df.shape).any(1)]

code tag number floor note
1 1111 * ** 34 no
3 3677 # 900 11 no
4 9897 10 134 * no
5 # # 566 11 no

选项 4
使用 map

在顶部
df[list(
map(bool,
map({'*', '**', '#'}.intersection,
map(set,
zip(*(df[c].values.tolist() for c in df)))))
)]

code tag number floor note
1 1111 * ** 34 no
3 3677 # 900 11 no
4 9897 10 134 * no
5 # # 566 11 no

关于python - 过滤列中包含特定值的行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45947302/

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