Reputation: 315
Lets say I have the following DataFrame:
X,Y,Z
a,b,c
d,e,m
h,i,m
k,l,m
I want to be able to use the .apply method to call a function on this dataframe, so like df.apply(modFunc())
to be able to change all the m
values in column Z to o
, so the result is
X,Y,Z
a,b,c
d,e,o
h,i,o
k,l,o
This is my try, so far I haven't found the solution:
def replaceFunc():
df['X'] = df.X.str.replace("m", "o")
df.apply(replaceFunc())
Doing this I get the following error:
TypeError: ("'NoneType' object is not callable", 'occurred at index STATION')
Upvotes: 2
Views: 1049
Reputation: 862406
If want use apply
is possible add axis=1
for processes by rows of DataFrame
s:
def replaceFunc(x):
x['Z'] = x.Z.replace("m", "o")
return x
df1 = df.apply(replaceFunc, axis=1)
Your solution should be changed by DataFrame.pipe
for processing DataFrame in function:
def replaceFunc(x):
x['Z'] = x.Z.str.replace("m", "o")
return x
df1 = df.pipe(replaceFunc)
Alternative:
df1 = replaceFunc(df)
Upvotes: 1