0

I have the following code for a table:

n_area = pd.crosstab(index=airbnb["neighbourhood"], columns=airbnb["neighbourhood_group"])

and I would like to add a row of totals (count) in the end of each column with a single function, completing what I have already written

this all comes from the dataset here https://www.kaggle.com/code/dgomonov/data-exploration-on-nyc-airbnb/data

A screenshot of the data is as follows

enter image description here

  • 1
    Hi, please also include sample data for us to know how we can help you. Thanks! –  Sep 02 '22 at 01:37
  • It is better if you provide sample data ready to go to help you. Kindly read: https://stackoverflow.com/help/how-to-ask – Luis Alejandro Vargas Ramos Sep 02 '22 at 01:41
  • It sounds like you're looking for `n_area = pd.crosstab(index=airbnb["neighbourhood"], columns=airbnb["neighbourhood_group"], margins=True).iloc[:, :-1]` (like in [this answer](/a/52440679/15497888)) – Henry Ecker Sep 02 '22 at 01:45
  • Hey Daniel, It would be great if you can include some sample data or minimally screenshots to better help other users to understand your question and assist you accordingly. That said, if I am interpretation your correctly, you are trying to get the subtotal of each row and columns. You can try: pd.crosstab(index=airbnb["neighbourhood"], columns=airbnb["neighbourhood_groupm"], margins = True, margins_name = Total) The `margins` parameter adds the subtotal at the end of both of the row and column that will sum up each of your neighbourhood and the groups. – ahjim0m0 Sep 02 '22 at 01:53
  • I was used to ask in R and use dput to generate an example. Is there a similar way to do this with python @ahjim0m0 – Daniel Ortiz Sep 02 '22 at 02:00
  • Hey Dan, I am not too familiar with R but you can try the `addmargin()` function. This is from a site: https://techvidvan.com/tutorials/r-contingency-tables/ 1. You will first have to ensure that it's a contingency table with the `tbl <- table(data$feature1, data$feature2, dnn = c("feature1", "feature2"))` function 2. Next using `addmargin(tbl)` and it should return you the subtotals for both rows and columns. – ahjim0m0 Sep 02 '22 at 05:33

0 Answers0