2017-04-18 16 views
1

我正在使用apply方法將數據從Pandas DataFrame發送到函數。如果單元格爲空白,則對象類型爲「NoneType」或「float」,這與我的函數所做的字符串比較不兼容。我過濾掉使用此數據:用Pandas過濾掉空的DataFrame單元的最佳方法適用

if isinstance(col1,str): #to make sure the data is a string. 

我的問題是,如果有更好的方法來做到這一點,因爲這違背了鴨子類型的概念?

對於這裏的上下文是我的代碼:

def check_cols(col1,col2): 
    if isinstance(col1,str): 
     var = col1 
    else: 
     var = col2 
    #the logical part of the function is here 

#passing in data from two columns 
dfcat['col3'] = dfcat.apply(lambda x: check_cols(x['col1'],x['col2']),axis=1) 

回答

1

我認爲,如果需要更換NoneNaN您可以使用combine_first

dfcat['col3'] = dfcat['col1'].combine_first(dfcat['col2']) 

但如果需要boolean mask更換非strings使用mask

mask = dfcat['col1'].apply(lambda x: isinstance(x,str)) 
dfcat['col3'] = dfcat['col2'].mask(mask, dfcat['col1']) 

示例:

dfcat = pd.DataFrame({'col1':[np.nan, 'aa', None, 10, 12.7], 'col2':['e','r','t','k', 'g']}) 
print (dfcat) 
    col1 col2 
0 NaN e 
1 aa r 
2 None t 
3 10 k 
4 12.7 g 

mask = dfcat['col1'].apply(lambda x: isinstance(x,str)) 
dfcat['col3'] = dfcat['col2'].mask(mask, dfcat['col1']) 
print (dfcat) 
    col1 col2 col3 
0 NaN e e 
1 aa r aa 
2 None t t 
3 10 k k 
4 12.7 g g 
+0

很好的例子,非常有幫助! – sparrow

相關問題