skrtel1503
skrtel1503

Reputation: 21

Creating a Function to use for dataframe

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

Answers (2)

MarianD
MarianD

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:

  1. In the first command (in the body of the function definition) we assign the appropriate column (i.e. a series) to the variable s.

  2. In the second command we apply the method .mask() with 2 arguments:

    • The first argument is a condition for using the second argument,
    • the second argument is a function (which is used only for elements satisfying the condition given in the first argument).

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

Anurag Dabas
Anurag Dabas

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

Related Questions