2017-07-26 148 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 
相關問題