0

I want to separate the cross table from single to multiple accprding to the given column list against the last column(CLASS). THE DATA IN THE TABLE LOOKS LIKE

GND  | BRD | ERS | CLASS
 F   |  A  |  AB |  ON
 M   |  D  |  CB |  ON
 M   |  S  |  AV |  ON
 F   |  S  |  AV |  OFF
 M   |  S  |  CB |  ON

This means that the last column against first column, last column agasinst next column

tried

#after loading dataframe
 g = pandas....
 #now
 idx = [g.GND g.BRD, g.ERS]     
    def cross_tb(inx):
        dt = pd.crosstab(inx,   g.CLASS)
        return dt   
    cross_tb(idx)

THIS GIVES SINLE TABLE WHICH LOOK LIKE

       F  M  A  D  S  AB  AV  CB
CLASS                           
OFF    1  0  0  0  1   0   1   0
ON     1  3  1  1  2   1   1   2

But I want to separate them once against CLASS one by one table like

  First one output      
    CLASS OFF ON  PERCENTAGE                          
    F     1   1     20%
    M     0   3     30%
  second output  A AND D etc..

But if you do this

 dt = pd.crosstab(g.GND,   g.CLASS)

it gives single column until you write the line again with other column

zuma boy
  • 15
  • 2

1 Answers1

0

IIUC, you can save the results of the crosstab to a dictionary:

df_dict = {c: pd.crosstab(df[c], df["CLASS"]) for c in df.columns if c!="CLASS"}

>>> df_dict["GND"]
CLASS  OFF  ON
GND           
F        1   1
M        0   3
not_speshal
  • 22,093
  • 2
  • 15
  • 30
  • @not_special this gives a single combined but also i get the same thing on my code above, I want to separate the please read the question – zuma boy Aug 02 '23 at 14:50
  • You did not provide your expected output. How do you expect to save/display 3 different tables. Do you want to create a list of DataFrames? Or just print the results without saving? – not_speshal Aug 02 '23 at 14:54
  • @not_special I want 3 separate table but without duplicating the cross tab function – zuma boy Aug 02 '23 at 15:01
  • So just save it to a `list` or `dict`. See the edit. – not_speshal Aug 02 '23 at 17:18