根据 Pandas 中的列表选择数据框行的子集 [英] Select subset of Data Frame rows based on a list in Pandas

查看:64
本文介绍了根据 Pandas 中的列表选择数据框行的子集的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个数据框 df1 和列表 x:

I have a data frame df1 and list x:

In [22] : import pandas as pd
In [23]: df1 = pd.DataFrame({'C': range(5), "B":range(10,20,2), "A":list('abcde')})
In [24]: df1
Out[24]:
   A   B  C
0  a  10  0
1  b  12  1
2  c  14  2
3  d  16  3
4  e  18  4

In [25]: x = ["b","c","g","h","j"]

我想要做的是根据列表选择数据框中的行.返回

What I want to do is to select rows in data frame based on the list. Returning

   A   B  C
1  b  12  1
2  c  14  2

有什么办法呢?我试过了,但失败了.

What's the way to do it? I tried this but failed.

df1.join(pd.DataFrame(x),how="inner")

推荐答案

使用 isin 返回一个布尔索引供您索引到您的 df:

Use isin to return a boolean index for you to index into your df:

In [152]:

df1[df1['A'].isin(x)]
Out[152]:
   A   B  C
1  b  12  1
2  c  14  2

这是 isin 返回的内容:

In [153]:

df1['A'].isin(x)
Out[153]:
0    False
1     True
2     True
3    False
4    False
Name: A, dtype: bool

这篇关于根据 Pandas 中的列表选择数据框行的子集的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆