逐列应用函数以进行原地编辑:
In [194]: df = pd.DataFrame({"A": ["FOO","BAAR","FOO"], "B": ["FOO","BAR" , "FOO"]})
In [195]: df.loc[:,["A","B"]].apply(lambda col : col.str.lower(), axis = 0) # axis= 0, Default in pandas
Out[195]:
A B
0 foo foo
1 baar bar
2 foo foo
逐行应用函数以进行必要的原地编辑:
In [201]: df.loc[:,["A","B"]].apply(lambda row : row.str.lower(), axis = 1)
Out[201]:
A B
0 foo foo
1 baar bar
2 foo foo
使用按列和按行应用函数的其他有用操作:
# For column-wise operation using apply function:
In [224]: df = pd.DataFrame({"A": ["FOO","BAAR","FOO"], "B": ["FOO","BAR" , "FOO"]})
In [225]: df.loc[:,["A","B"]].apply(lambda col : col.str.lower() + "_" + "cool" + "_" + df["B"])
Out[225]:
A B
0 foo_cool_FOO foo_cool_FOO
1 baar_cool_BAR bar_cool_BAR
2 foo_cool_FOO foo_cool_FOO
#Note only second element from each column is taken as an argument for lambda function, so NaN for others:
In [226]: df.loc[:,["A","B"]].apply(lambda col : col[1:2].str.lower() + "_"+ "cool" + "_" + df["B"])
Out[226]:
A B
0 NaN NaN
1 baar_cool_BAR bar_cool_BAR
2 NaN NaN
#For Row-wise operation (row[0] & row[1] points to first and second element of each row,
#or can be called as row["A"] $ row["B"] respectively ):
In [207]: df.loc[:,["A","B"]].apply(lambda row : row["B"].lower() + "_" + row["A"].lower() , axis = 1)
Out[207]:
0 foo_foo
1 bar_baar
2 foo_foo
dtype: object
In [208]: df.loc[:,["A","B"]].apply(lambda row : row[1].lower() + "_" + row[0].lower() , axis = 1)
Out[208]:
0 foo_foo
1 bar_baar
2 foo_foo
dtype: object
#Here, row[1] indicates second element of each row, i.e row["B"] :
In [235]: df.loc[:,["A","B"]].apply(lambda row : row.str.lower() + "_"+ row[1], axis = 1)
Out[235]:
A B
0 foo_FOO foo_FOO
1 baar_BAR bar_BAR
2 foo_FOO foo_FOO
apply
。如果你不确定是否需要使用它,那么你可能不需要。我建议看一下《何时应该在代码中使用pandas apply()函数?》。 - cs95