Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

calculate std for Pandas DataFrame grouped by object data type column

i have pandas dataframe with numeric and object data type columns

code of input

import pandas as pd

data = {
    'country_code': ['AFG', 'AGO', 'ALB', 'ARE', 'ARG'],
    'country_name': ['Afghanistan', 'Angola', 'Albania', 'United Arab Emirates', 'Argentina'],
    'continent': ['Asia', 'Africa', 'Europe', 'Asia', 'South America'],
    2010: [11.35, 9.43, 14.09, 2.48, 7.71],
    2011: [11.05, 7.36, 13.48, 2.30, 7.18],
    2012: [11.34, 7.35, 13.38, 2.18, 7.22],
    2013: [11.19, 7.37, 15.87, 2.04, 7.10],
    2014: [11.14, 7.37, 18.05, 1.91, 7.27]
}

df = pd.DataFrame(data)

i try to calculate stdev for the dataframe columns grouped by object data frame column(continent).

so if i have columns with object data type i should get the numeric one's, but the problem is when to get the numeric columns i will not able to see the the object data type column(continent).

df.select_dtypes('number').groupby('continent').std()

is there another way to make it ??

like image 872
M.Shaker Nayyal Avatar asked Jan 20 '26 12:01

M.Shaker Nayyal


1 Answers

Suppose you have thid df:

  country_code country_name continent  2010  2011
0            A            A    Europe     1    40
1            B            B    Europe     2     5
2            C            C   America     3    60
3            D            D   America     4     7

Then you can do:

out = df.groupby("continent").apply(
    lambda x: x.select_dtypes("number").std(), include_groups=False
)
print(out)

Prints:

               2010       2011
continent                     
America    0.707107  37.476659
Europe     0.707107  24.748737
like image 65
Andrej Kesely Avatar answered Jan 22 '26 02:01

Andrej Kesely



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!