In this article we will discuss different ways to apply a given function to selected columns or rows.

Suppose we have a dataframe object i.e.

Contents of the dataframe object dfObj are,

Now if we want to call / apply a function on all the elements of a single or multiple columns or rows ? For example,

  • Multiply all the values in column ‘x’ by 2
  • Multiply all the values in row ‘c’ by 10
  • Add 10 in all the values in column ‘y’ & ‘z’

Let’s see how to do that using different techniques,

Apply a function to a single column in Dataframe

Suppose we want to square all the values in column ‘z’ for above created dataframe object dfObj. We can do that using different methods i.e.

Method 1 : Using Dataframe.apply()

Apply a lambda function to all the columns in dataframe using Dataframe.apply() and inside this lambda function check if column name is ‘z’ then square all the values in it i.e.

Output:

There are 2 other ways to achieve the same effect i.e.

Method 2 : Using [] Operator

Select the column from dataframe as series using [] operator and apply numpy.square() method on it. Then assign it back to column i.e.

It will basically square all the values in column ‘z’

Method 3 : Using numpy.square()

It will also square all the values in column ‘z’

Apply a function to a single row in Dataframe

Suppose we want to square all the values in row ‘b’ for above created dataframe object dfObj. We can do that using different methods i.e.

Method 1 : Using Dataframe.apply()

Apply a lambda function to all the rows in dataframe using Dataframe.apply() and inside this lambda function check if row index label is ‘b’ then square all the values in it i.e.

Output:

There are 2 other ways to achieve the same effect i.e.

Method 2 : Using [] Operator

Select the row from dataframe as series using dataframe.loc[] operator and apply numpy.square() method on it. Then assign it back to row i.e.

It will basically square all the values in row ‘b’

Method 3 : Using numpy.square()

It will also square all the values in row ‘b’.

Apply a function to a certain columns in Dataframe

We can apply a given function to only specified columns too. For example square the values in column ‘x’ & ‘y’ i.e.

Output:

Basically we just modified the if condition in lambda function and squared the values in columns with name x & y.

Apply a function to a certain rows in Dataframe

We can apply a given function to only specified rows too. For example square the values in column ‘b’ & ‘c’ i.e.

Output:

Basically we just modified the if condition in lambda function and squared the values in rows with name b & c.

Complete example is as follows :

Output:

 

Python Resources

C++11 / C++14 Resources

Design Patterns Resources

If you didn't find what you were looking, then do suggest us in the comments below. We will be more than happy to add that.

Do Subscribe with us for more Articles / Tutorials like this,