Reputation: 21
How can I create a function that squares the specific column value from a dataframe in pandas?
it should be like as you see below
def func(dataframe,column,value)
Upvotes: 2
Views: 1114
Reputation: 14121
I suppose that you wanted to square only those values in the column
column which are equal to value
parameter:
def func(dataframe, column, value):
s = dataframe[column]
dataframe[column] = s.mask(s == value, lambda x: x**2)
Note:
This function changes the dataframe in place, so in concordance with Python conventions it returns the None
value. (Why? Because there is no return
statement.)
The explanation:
In the first command (in the body of the function definition) we assign the appropriate column (i.e. a series) to the variable s
.
In the second command we apply the method .mask()
with 2 arguments:
A test:
>>> df
A B C D 0 4 4 3 4 1 3 3 4 4 2 4 4 2 2 3 3 2 3 4 4 4 2 4 3
>>> func(df, "D", 4)
>>> df
A B C D 0 4 4 3 16 1 3 3 4 16 2 4 4 2 2 3 3 2 3 16 4 4 2 4 3
Upvotes: 1
Reputation: 24304
Suppose you have dataframe named df
Just create a function:-
def pow(data,column,val):
return data[column]**val
Now just call the function and pass the series,and val as parameter:-
func(df,'col3',2)
Between you can do this without creating a function just by:-
df['column name']**2
Upvotes: 1