适用于过滤掉带有Pandas的空DataFrame单元格的最佳方法

时间:2017-04-18 13:56:13

标签: python pandas

我正在使用apply方法将数据从Pandas DataFrame发送到函数。如果单元格为空,则对象类型为“NoneType”或“float”,这与我的函数所做的字符串比较不兼容。我正在使用以下方法过滤掉这些数据:

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 个答案:

答案 0 :(得分:1)

我认为如果需要替换NoneNaN,您可以使用combine_first

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

但如果需要将strings替换为boolean 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

样品:

html, body {
  min-height: 100%;
  height: auto;
  margin: 0;
}