3

I have a table where similar to"

no   type    category    a     b    c    d
1    plan      avg       5     4    3    
2    plan      avg             3         3
3    plan      est       2     1         2
4    plan      est       6     4   
5    forecast  avg             4         3

I want to create a new column where it will count number of columns that have value in the 4 last columns.

no   type    category  counts  
1    plan      avg       3
2    plan      avg       2
3    plan      est       3
4    plan      est       2
5    forecast  avg       2

How can I do that in python?

Thanks in advance.

1
  • 1
    You could use count() method directly for the dataframe. The count() method returns the number of non-NaN values in each column. Commented Mar 29, 2021 at 15:30

2 Answers 2

3

Try with

df['New'] = df.iloc[:,-4:].ne('').sum(axis=1)
Sign up to request clarification or add additional context in comments.

Comments

1

This is the fastest and most efficient way to do the job also you can specify if only numeric values have to be counted

  df['counts']=df.iloc[:, -4:].count(numeric_only=True,axis=1)

You can count the number of values in columns as well instead of rows by using axis=0 checkout df.count() for more info.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.