Math operations across all columns of a pandas dataframe, regardless of its size

Viewed 540
import pandas as pd
import numpy as np
d = {'col1': [100, 198, 495, 600, 50], 'col2': [99, 200, 500, 594, 100], 'col3': [101, 202, 505, 606, 150]}
df = pd.DataFrame(data=d)
df

From this I get a simple table:

    col1    col2    col3
0   100     99      101
1   198     200     202
2   495     500     505
3   600     594     606
4   50      100     150

From this I would like to take the %CV of all values in the first row, then second rows and so on...

I would like that it works regardless of how many columns the table has.

I could do this with a few lines of code:

df_shape = df.shape
CV_list = []
for i in range(df_shape[0]):
    CV = np.std(df.iloc[i, :], ddof=1) / np.mean(df.iloc[i, :]) * 100
    CV_list.append(str(round(CV, 3)) + ' %')
df["cv"] = CV_list
df

output:

    col1    col2    col3    CV
0   100     99      101     1%
1   198     200     202     1%
2   495     500     505     1%
3   600     594     606     1%
4   50      100     150     50%

But I wonder if Pandas has a built in functions for this (that I could not find so far).

1 Answers

You can operate across an entire row by specifying axis=1. So get the Series of standard deviations and means (for each row) and divide.

df['CV'] = df.std(axis=1, ddof=1)/df.mean(axis=1)*100

   col1  col2  col3    CV
0   100    99   101   1.0
1   198   200   202   1.0
2   495   500   505   1.0
3   600   594   606   1.0
4    50   100   150  50.0
Related