How to load scipy.stats.describe output into a pandas dataframe?

Viewed 1745

Is there an easy and straightforward way to load the output from sp.stats.describe() into a DataFrame, including the value names? It doesn't seem to be a dictionary format or something related. Ofcourse I can manually attach the relevant column names (see below), but was wondering whether it might be possible to directly load into a DataFrame with named columns.

import pandas as pd
import scipy as sp

data = pd.DataFrame({'a': [1, 2, 3, 4, 5], 'b': [1, 2, 3, 4, 5]})

sp.stats.describe(data['a'])

pd.DataFrame(a)

pd.DataFrame(a).transpose().rename(columns={0: 'N', 1: 'Min,Max',
                                            2: 'Mean', 3: 'Var',
                                            4: 'Skewness',
                                            5: 'Kurtosis'})
1 Answers

You can use _fields for columns names from named tuple:

a = sp.stats.describe(data['a'])
df = pd.DataFrame([a], columns=a._fields)
print (df)
   nobs  minmax  mean  variance  skewness  kurtosis
0     5  (1, 5)   3.0       2.5       0.0      -1.3

Also is possible create dictionary from named tuples by _asdict:

d = sp.stats.describe(data['a'])._asdict()
df = pd.DataFrame([d], columns=d.keys())
print (df)
   nobs  minmax  mean  variance  skewness  kurtosis
0     5  (1, 5)   3.0       2.5       0.0      -1.3 
Related