0

Attached image

df_top4 as below

I have a dataframe (df_top4) as below and I want to divide the entire row by total, without dividing it by itself. Is there a way I could preserve my total as I need to make a bar chart of subject vs total?

df_top4=df_top4.divide(df_top4.total, axis=0)

Also I want to retain the total field hence this olution(Pandas sum across columns and divide each cell from that value) didnt work

  • Use `cols = df.filter(like='Student').columns` and then `df[cols] = df[cols].div(df['Total'], axis=0)` – jezrael Oct 26 '20 at 10:52

1 Answers1

1

Use:

mask = df.columns.str.contains('Student')
df.loc[:, mask] = df.loc[:, mask].div(df['Total'], axis=0)
jezrael
  • 822,522
  • 95
  • 1,334
  • 1,252
ansev
  • 30,322
  • 5
  • 17
  • 31
  • Hi Ansev, I followed he method but getting this - ' ' 2789 # Do we have a (boolean) 1d indexer? 2790 if com.is_bool_indexer(key): -> 2791 return self._getitem_bool_array(key) 2792 2793 # We are left with two options: a single key, and a collection of keys, 2835 ) 2836 elif len(key) != len(self.index): -> 2837 raise ValueError( 2838 f"Item wrong length {len(key)} instead of {len(self.index)}." 2839 ) ' – xnorphic2652 Oct 26 '20 at 10:31
  • @xnorphic2652 - Answer was edited – jezrael Oct 26 '20 at 10:52