2017-07-26 72 views
1

有一个大熊猫数据框:如何创建从另一个数据框中一个新的数据帧,并在大熊猫名单

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 

如何创建一个新的数据帧包含c1在list1中的行。

输出:

c1 c2 
0 b 2 
1 c 3 
+0

可能使用[使用v从熊猫数据框选择行的线索​​](https://stackoverflow.com/questions/12096252/use-a-list-of-values-to-select-rows-from-a-pandas-dataframe) – Zero

回答

3

使用query

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 
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 
+0

@piRSquared Trust我,如果有一个很好的答案,那么你会更好地发现它:) –

2

两个@ JohnGalt的和@ COLDSPEED的答案是更地道pandas。请不要使用这些答案。它们旨在成为pandasnumpy API的其他部分的有趣和说明。

Alt键1
这是利用numpy.in1d充当代理用于pd.Series.isin

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

    c1 c2 
1 b 2 
2 c 3 

Alt键2
使用set逻辑

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 
+1

现在它变得非常具有挑战性,找到另一种方式来做到这一点...;) – MaxU

+0

更好的+1之前,熊猫人来了,让你感到困扰为了使用numpy:^) –

+0

@cᴏʟᴅsᴘᴇᴇᴅ我们很好( - :我通过把它叫出来让每个人都做对了。 – piRSquared

0

对于completenes

另一种方式的缘故(绝对不是最好的一个),以实现:

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