Pandas DataFrame Multi Index Summation

Let's say I create the following data file with df.set_index ('Class', 'subclass'), bearing in mind that there are several classes with subclasses ... A> Z.

Class   subclass    
  A       a           
  A       b 
  A       c 
  A       d 
  B       a            
  B       b 

How do I count subclasses in a class and create a separate column named no classes so that I can see the class with the most subclasses? I was thinking of some kind of loop that runs through the letters of the class and counts the subclass if this class letter is anyway. However, for such a problem, this seems a bit controversial. Would there be a simpler approach, for example, df.groupby [] count?

Desired Result:

Class   subclass    No. of classes
  A       a                4    
  A       b 
  A       c 
  A       d 
  B       a                2    
  B       b 

I tried the level parameter as shown in the pandas dataframe group multi-index , but for me it does not work

EDIT:

, . :

df.reset_index().groupby('Class')['subclass'].nunique().idxmax()
+4
2

transform, :

df['No. of classes'] = df.groupby(level='Class')['val'].transform('size')

print (df)
                val  No. of classes
Class subclass                     
A     a           1               4
      b           4               4
      c           5               4
      d           4               4
B     a           1               2
      b           2               2

:

df['No. of classes'] = df.groupby(level='Class')
                         .apply(lambda x: pd.Series( [len(x)] + [np.nan] * (len(x)-1)))
                         .values
print (df)
                val  No. of classes
Class subclass                     
A     a           1             4.0
      b           4             NaN
      c           5             NaN
      d           4             NaN
B     a           1             2.0
      b           2             NaN

get Class :

df = df.groupby(level=['Class'])
       .apply(lambda x: x.index.get_level_values('subclass').nunique())
       .idxmax()
print (df)
A
+3

transform, df :

In [165]:
df['No. of classes'] = df.groupby('Class')['subclass'].transform('count')
df

Out[165]:
  Class subclass  No. of classes
0     A        a               4
1     A        b               4
2     A        c               4
3     A        d               4
4     B        a               2
5     B        b               2
+2

Source: https://habr.com/ru/post/1667870/


All Articles