![](/img/trans.png)
[英]apply() to every column of every dataframe of an ExcelFile, Pandas
[英]Pandas apply & map to every element of every column
如果其值不为null,如何将自定义函数应用于每个列的每个元素?
可以说我有一个10列的数据框,如果pd.notnull(x),我想在其中应用一个lower()函数到只有4列的每个元素上,否则就不保留任何值。
我试图这样使用
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.
如何摆脱这个错误?
我认为您需要DataFrame.applymap
因为按DataFrame.applymap
工作:
L = [[1.5, 'Test', np.nan, 2], ['Test', np.nan, 2,'TEST'], ['Test', np.nan,1.5, 2]]
df = pd.DataFrame(L, columns=list('abcd'))
print (df)
a b c d
0 1.5 Test NaN 2
1 Test NaN 2.0 TEST
2 Test NaN 1.5 2
cols = ['a','b']
#for python 2 change str to basestring
df[cols] = df[cols].applymap(lambda x: x.lower() if isinstance(x, str) else x)
print (df)
a b c d
0 1.5 test NaN 2
1 test NaN 2.0 TEST
2 test NaN 1.5 2
您尝试映射一个Series,然后在lambda中占据整行。
您还应该检查没有方法.lower()的整数,浮点数等。 因此,我认为最好的方法是检查它是否是字符串,而不仅仅是检查它是否不是非空值。
这有效:
s = pd.DataFrame([{'A': 1.5, 'B':"Test", 'C': np.nan, 'D':2}])
s
A B C D
0 1.5 Test NaN 2
s1 = s.apply(lambda x: x[0].lower() if isinstance(x[0], basestring) else x[0]).copy()
s1
A 1.5
B test
C NaN
D 2
dtype: object
对于python 3,检查字符串isinstance(x[0], str)
为了能够选择列:
s1 = pd.DataFrame()
columns = ["A", "B"]
for column in columns:
s1[column] = s[column].apply(lambda x: x.lower() if isinstance(x, str) else x).copy()
s1
A B
0 1.5 test
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.