juststuck
juststuck

Reputation: 656

How to count instances of a character or number in whole DataFrame?

Let's say i have list of data frames month[1..12], each with 10 rows and 30 columns filled with numbers 0, 1 and sometimes "N".

I have to count number of instances for each 0, 1 and "N" in each data frame. Desired outcome would be something like:

month[1].stack().value_counts()

1: 200
0: 80 
"N": 20 

Unfortunately, above code gives incorrect answer. How would you approach this questions with other methods?

Upvotes: 0

Views: 84

Answers (1)

A simple way of approaching this would be to convert the data frame into a list and perform a count function to obtain the quantities of N, 0 and 1. I have build a simple routine to do this:

def get_instances(df, instance):
    df_list = df.values.tolist()
    return sum([index.count(instance) for index in df_list])

You can then find the instances of 'N' in month[1] for example by executing the routine with the following parameters:

get_instances(month[1], 'N')

Upvotes: 1

Related Questions