根据列值删除Pandas中的DataFrame行

根据列值删除Pandas中的DataFrame行

本文介绍了根据列值删除Pandas中的DataFrame行 - 要删除的多个值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的Panda DataFrame中的列不能包含所有行的值列表(事先未知,在Python列表中)。



所有Web上的食谱(如)显示如何做到只有一个值排除,但我有多个值要排除。如何做?



请注意,我无法对代码中的值进行硬编码。



谢谢!

解决方案

你可以做消极的函数:

 在[60]中:df.query('@ my_list不在b')
输出[60]:
abc
0 1 2 2
3 3 2 7
4 1 3 1
5 3 4 2
7 5 4 3
9 3 2 0


I have a list of values (not known in advance, in a Python list) that a column in my Panda DataFrame must not have for all rows.

All recipes on the Web (like this one) show how to do it with only one value to exclude, but I have multiple values to exclude. How do I do it?

Please note that I cannot hardcode the values to exclude in my code.

Thanks!

解决方案

You can do negative isin() indexing:

In [57]: df
Out[57]:
   a  b  c
0  1  2  2
1  1  7  0
2  3  7  1
3  3  2  7
4  1  3  1
5  3  4  2
6  0  7  1
7  5  4  3
8  6  1  0
9  3  2  0

In [58]: my_list = [1, 7, 8]

In [59]: df.ix[~df.b.isin(my_list)]
Out[59]:
   a  b  c
0  1  2  2
3  3  2  7
4  1  3  1
5  3  4  2
7  5  4  3
9  3  2  0

or using query() function:

In [60]: df.query('@my_list not in b')
Out[60]:
   a  b  c
0  1  2  2
3  3  2  7
4  1  3  1
5  3  4  2
7  5  4  3
9  3  2  0

这篇关于根据列值删除Pandas中的DataFrame行 - 要删除的多个值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-30 03:07
查看更多