neuniversity / ALY6140

1 stars 3 forks source link

How to count the number of the same name in the column? #34

Open ZelingJiang opened 5 years ago

ZelingJiang commented 5 years ago

I have a column named 'Month'. Now I want to know how many times for each month appears in the column. And I want a table, not just a number.

What I thought is I add a new column assigned number '1' in it. And use groupby('Month').agg([np.sum]) function.

Does anyone have some smarter ideas?

ShailuKonda commented 5 years ago

I think you can use "value_counts()" function to count number of repeated items in a column. I am not sure. Try once.

ThatkidfromA commented 5 years ago

Hello, After using the groupby function, I think you should include transform in the argument. Therefore it will create another column in the data frame.

I hope the link will help you and If the argument is confusing, you should check the documentation. https://stackoverflow.com/questions/29836477/pandas-create-new-column-with-count-from-groupby

CHENGYULIU1 commented 5 years ago

Use .value_counts() function. if you want to put in the table use pd.DataFrame() funxtion

Example: pd.DataFrame(loandf["Gender"].value_counts())

Jin-pengSong commented 5 years ago

I often use value_counts() to do that

ZelingJiang commented 5 years ago

Anyway, thank you for your answer Song. But what I want is a table, not just a number!

shahtrupt commented 5 years ago

You can try using the below code to solve your issue. It is just another way to get the counts of unique values observed in a column. unique_elements, counts_elements = np.unique(df['Month'], return_counts=True) print(unique_elements, counts_elements) I hope this helps!