如何将自定义函数应用于每列的每个元素,如果该值不为null?
假设我有一个由10列组成的数据框,其中我想对其中4列的每个元素应用lower()函数,如果pd.notnull(x),否则只保留值为none。
我尝试像这样使用:
s.apply(lambda x: change_to_lowercase(x), axis = 1)
def change_to_lowercase(s):
s['A'] = s['A'].map(lambda x: x.lower() if pd.notnull(x) else x)
s['B'] = s['B'].map(lambda x: x.lower() if pd.notnull(x) else x)
s['C'] = s['C'].map(lambda x: x.lower() if pd.notnull(x) else x)
s['D'] = s['D'].map(lambda x: x.lower() if pd.notnull(x) else x)
return s
但是由于我的列是混合数据类型(NaN为浮点数,其余为Unicode),这导致了错误 -
float has no attribute map.
如何摆脱这个错误?