Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/335.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 按列表中的值筛选数据帧_Python_Pandas_List_Dataframe - Fatal编程技术网

Python 按列表中的值筛选数据帧

Python 按列表中的值筛选数据帧,python,pandas,list,dataframe,Python,Pandas,List,Dataframe,有一个数据帧: df = pd.DataFrame({'c1':['a','b','c','d'],'c2':[1,2,3,4]}) c1 c2 0 a 1 1 b 2 2 c 3 3 d 4 以及熊猫系列: list1 = pd.Series(['b','c','e','f']) Out[6]: 0 a 1 b 2 c 3 e 如何创建包含列表1中c1所在行的新数据框 输出: c1 c2 0 b 2 1 c

有一个数据帧:

  df = pd.DataFrame({'c1':['a','b','c','d'],'c2':[1,2,3,4]})

c1  c2
0   a   1
1   b   2
2   c   3
3   d   4
以及熊猫系列:

list1 = pd.Series(['b','c','e','f'])

Out[6]:
0    a
1    b
2    c
3    e
如何创建包含列表1中c1所在行的新数据框

输出:

c1  c2
0   b   2
1   c   3 

使用
查询

In [1133]: df.query('c1 in @list1')
Out[1133]:
  c1  c2
1  b   2
2  c   3
或者,使用
isin

In [1134]: df[df.c1.isin(list1)]
Out[1134]:
  c1  c2
1  b   2
2  c   3

使用
查询

In [1133]: df.query('c1 in @list1')
Out[1133]:
  c1  c2
1  b   2
2  c   3
或者,使用
isin

In [1134]: df[df.c1.isin(list1)]
Out[1134]:
  c1  c2
1  b   2
2  c   3

您可以使用
df.isin

In [582]: df[df.c1.isin(list1)]
Out[582]: 
  c1  c2
1  b   2
2  c   3
或者,如果要修改切片,请使用
df.loc

In [584]: df.loc[df.c1.isin(list1), :]
Out[584]: 
  c1  c2
1  b   2
2  c   3

您可以使用
df.isin

In [582]: df[df.c1.isin(list1)]
Out[582]: 
  c1  c2
1  b   2
2  c   3
或者,如果要修改切片,请使用
df.loc

In [584]: df.loc[df.c1.isin(list1), :]
Out[584]: 
  c1  c2
1  b   2
2  c   3

@JohnGalt和@COLDSPEED的答案都更加地道。请不要使用这些答案。它们旨在使
pandas
numpy
api的其他部分变得有趣和具有说明性

Alt 1
这是利用
numpy.inad
作为
pd.Series.isin的代理

df[np.in1d(df.c1.values, list1.values)]

  c1  c2
1  b   2
2  c   3

Alt 2
使用
设置
逻辑

df[df.c1.apply(set) & set(list1)]

  c1  c2
1  b   2
2  c   3

Alt 3
使用
pd.Series.str.match

df[df.c1.str.match('|'.join(list1))]

  c1  c2
1  b   2
2  c   3

@JohnGalt和@COLDSPEED的答案都更加地道。请不要使用这些答案。它们旨在使
pandas
numpy
api的其他部分变得有趣和具有说明性

Alt 1
这是利用
numpy.inad
作为
pd.Series.isin的代理

df[np.in1d(df.c1.values, list1.values)]

  c1  c2
1  b   2
2  c   3

Alt 2
使用
设置
逻辑

df[df.c1.apply(set) & set(list1)]

  c1  c2
1  b   2
2  c   3

Alt 3
使用
pd.Series.str.match

df[df.c1.str.match('|'.join(list1))]

  c1  c2
1  b   2
2  c   3

为了完整的人

实现这一目标的另一种方法(肯定不是最好的方法):

In [4]: df.merge(list1.to_frame(name='c1'))
Out[4]:
  c1  c2
0  b   2
1  c   3

为了完整的人

实现这一目标的另一种方法(肯定不是最好的方法):

In [4]: df.merge(list1.to_frame(name='c1'))
Out[4]:
  c1  c2
0  b   2
1  c   3

现在,要想找到另一种方法来实现这一点,真的变得非常具有挑战性……;)更好的+1,在那个熊猫家伙来之前,他会因为你使用numpy而把你开除:^)@cᴏʟᴅsᴘᴇᴇᴅ 我们很好(:我对每个人都很好。现在找到另一种方法来做到这一点真的很有挑战性…;)更好+1,在那个熊猫家伙来因为你使用numpy而把你开除之前:^@cᴏʟᴅsᴘᴇᴇᴅ 我们很好(-:我对每个人都很好。