简体   繁体   中英

Pandas value_counts() alternative for a range of values?

I've been using value_count() to get the counts of unique values in individual rows of dataframe by doing the following:

data.iloc[i,2:-1].value_counts()

Is it possible to do that for a range of rows? I tried the following, but it didn't work, is it just printed out the range that I specified instead of counting the unique values:

data.iloc[0:5,2:-1].value_counts()

I would like a similar kind of output (a Series) that I can loop through using.items()

Any kind of help would be greatly appreciated! Thank you!

You can try apply :

data.iloc[0:5, 2:-1].apply(lambda x: x.value_counts(), axis=1)

But that would give you value counts for each row . So you would get a dataframe. Now if you want to count values in the whole data section, you can stack :

data.iloc[0:5, 2:-1].stack().value_counts()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM