-3

I am new to python pandas programming and trying to explore more on the cross tabulation. I have a requirement where I need to generate a cross table for multiple variables but with one constant variable. i.e. side as multiple variables and top one variable.

I have searched the web for my requirement however I could only find the cross tabulation among 2 or 3 variables only.

Coming to my requirement I have a dataset in data.csv file which I am reading as a dataframe

df = pd.read_csv('C:\Users\Desktop\data.csv')

Now I want to cross tabulate the dataframe (df) with one of the variable within this dataframe.

Like… pd.crosstab(df, df.age, margins=True)

example,

enter image description here

So could anyone help in solving this issue. Many thanks for the feedback.

help-ukraine-now
  • 3,850
  • 4
  • 19
  • 36
SUMAN SEN
  • 11
  • 4
  • 2
    Welcome to StackOverflow. Please take the time to read this post on [how to provide a great pandas example](http://stackoverflow.com/questions/20109391/how-to-make-good-reproducible-pandas-examples) as well as how to provide a [minimal, complete, and verifiable example](http://stackoverflow.com/help/mcve) and revise your question accordingly. These tips on [how to ask a good question](http://stackoverflow.com/help/how-to-ask) may also be useful. – jezrael Mar 21 '17 at 09:15

1 Answers1

0

Do you know pd.pivot_table() ?

In [139]: df
Out[139]: 
       a    b    c    d
0    5.1  3.5  1.4  0.2
1    4.9  3.0  1.4  0.2
2    4.7  3.2  1.3  0.2
3    4.6  3.1  1.5  0.2
4    5.0  3.6  1.4  0.2

then

In [138]: pd.pivot_table(df, index=['a','b','c'])
Out[138]: 
               d
a   b   c       
4.3 3.0 1.1  0.1
4.4 2.9 1.4  0.2
    3.0 1.3  0.2
    3.2 1.3  0.2
4.5 2.3 1.3  0.3
4.6 3.1 1.5  0.2
    3.2 1.4  0.2
    3.4 1.4  0.3
Hiroyuki
  • 26
  • 3
  • I have attached a sample report in the original post which shows how the tables should be. Here the variable YEAR is constant for all the variables of a data frame and the side variables i.e. VAR1, VAR2 & VAR3 are crosstabulated with the variable YEAR. – SUMAN SEN Mar 21 '17 at 10:45