2016-02-29 67 views
1

我想使用pandas根據給定列表刪除某些行,但也跳過那些不包含在我的數據框中的項目。從數據框中刪除行,但跳過軸中不包含的標籤

例如,

# My dataframe 
id,name 
A,Bill 
B,Lee 
C,Jack 

# id list that I want to take out 
id, 
A, 
E, # does not contain in data frame 
F, # does not contain in data frame 
G, # does not contain in data frame 

## I'd like to see in my result... 

id,name 
B,Lee 
C,Jack 

我試圖df[~df['id'].isin(given_id_list)]df.set_index('id').drop(given_id_list.set_index('id').index)但都不能很好工作。

任何明智的建議?

回答

1

這不是最「pythonic」的解決方案 - 但它的工作原理。循環索引,檢查ID變量,如果它在列表中,則將其放下。

import pandas as pd 
#create the sample dataframe 
data = {'id':['A','B','C'], 'name': ['jack', 'john', 'bill']} 
df = pd.DataFrame(data) 

#list of possible rows to drop: 
to_drop = ['A', 'F', 'G'] 

#loop thru each index 
for ix in df.index: 
    #check if it is a good one to drop 
    if df.loc[ix]['id'] in to_drop: 
     #drop it if it is 
     df.drop(ix, inplace = True) 
相關問題