1

I am trying to get the table() equivalent function(from R) in Python.

I have a table :

+-----+--------+
|  Sr | Gender |
+-----+--------+
| 123 |    M   |
+-----+--------+
| 124 |    M   |
+-----+--------+
| 126 |    M   |
+-----+--------+
| 127 |    F   |
+-----+--------+
| 128 |    F   |
+-----+--------+

Expected output :

+---+---+
| M | F |
+---+---+
| 3 | 2 |
+---+---+

in R it could be easily achieved by table(df$Gender)

But not sure how to achieve this in Python. I have tried crosstab() and pivot_table() but not able to get the exact syntax.

I'm the man.
  • 207
  • 2
  • 13
SKB
  • 189
  • 1
  • 13

1 Answers1

2

You can do it a few ways, depending on what you want to get:

df = pd.read_clipboard()

In [629]: df.Gender.value_counts()                                                                                                                                                             
Out[629]: 
M    3
F    2

or

print(pd.value_counts(df['Gender']).to_frame().T.to_string(index=False))                                                                                                             
 M  F
 3  2

In [630]: pd.DataFrame(df.Gender.value_counts())                                                                                                                                               
Out[630]: 
   Gender
M       3
F       2

In [632]: pd.DataFrame(df.Gender.value_counts()).T                                                                                                                                             
Out[632]: 
        M  F
Gender  3  2

or for your exact:

In [643]: pd.DataFrame(df.Gender.value_counts()).rename(columns={'Gender': ''}).T                                                                                                              

  M  F
  3  2
oppressionslayer
  • 6,942
  • 2
  • 7
  • 24