2

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)

2
  • You don't need to use a function. You can just do: df['column name'] = df['column name']**2 Commented Mar 3, 2021 at 13:20
  • I know that but I have to use that function Commented Mar 3, 2021 at 13:57

2 Answers 2

1

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
Sign up to request clarification or add additional context in comments.

5 Comments

Thanks for your answer.. Yes, I have a dataframe called df Your answers work too but i have to define that function as def func(dataframe,column,value)
Without using 'value' i figured out how to do it but i couldn't make it with 'value'. It is how it is without 'value' def func(df,column): df[column]=df[column]*df[column] return df
Thanks for helping so much but it's still not the one i need :(......your functions has data,val.... i need df,columnname,value
Heyyy :).... I did a small change to your last edit and it works... Thanks a lot!!
that's great............btw if this answer helps you then try considering accept this answer thank you:)
1

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

1 Comment

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.