pandas Python中根据索引值过滤数据框

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/53482760/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-14 06:10:42  来源:igfitidea点击:

Filter data frame based on index value in Python

pythonpandas

提问by RGRGRG

I have a data frame dfwith thousands of rows, and a sample is this:

我有一个df包含数千行的数据框,示例如下:

    Index           A   B   C   D   E   F               
    EX-A.1.A.B-1A  18   7   2   2   9   8       
    EX-A.1.A.B-1C   0   0   0   0   0   0       
    EX-A.1.A.B-4A   6   4   8   6   1   1   
    EX-A.1.A.B-4C   0   0   0   0   0   0   
    EX-A.1.A.B-4F   0   0   0   0   0   0

I also have a list my_list = ["EX-A.1.A.B-1A","EX-A.1.A.B-4A","EX-A.1.A.B-4F"]

我也有一份清单 my_list = ["EX-A.1.A.B-1A","EX-A.1.A.B-4A","EX-A.1.A.B-4F"]

and I want to filter the dfbased on this list, therefore I want to keep the rows for which the index value is in the list my_list.

并且我想df根据此列表过滤,因此我想保留索引值在列表中的行my_list

I tried this in order to create a new filtered df: Filter_df = df[df.index in my_list]and I get this error:

我尝试这样做是为了创建一个新的过滤 df:Filter_df = df[df.index in my_list]并且我收到此错误:

ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all().

Any ideas on how I could do this? Thanks

关于我如何做到这一点的任何想法?谢谢

回答by Alla Tarighati

try this:

尝试这个:

Filter_df  = df[df.index.isin(my_list)]