如果值不为空,如何将自定义函数应用于每列的每个元素?
假设我有一个包含 10 列的数据框,如果 pd.notnull(x),我想将一个 lower() 函数应用于只有 4 列的每个元素,否则只保留 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.
如何摆脱这个错误?