Home > Blockchain >  How to count item total for all rows in a dataframe
How to count item total for all rows in a dataframe

Time:03-10

I try to count the item total for all rows in a DataFrame. Is there a way to do it? In the dataset below, I try to count how many items are there across all columns and add a column at the end that show the total count.

For example, for item 1, it has value for period 2 and 3, thus the count is 2. For item 4, there is no value across all column, thus the count is 0.

import pandas as pd

df1 = { 'item':['item1','item2','item3','item4'],
  'period1':['','','5555',''],
  'period2':['4567','3333','',''],
  'period3':['1234', '','9993',''],
  'period4':['','','2345','']}

df1=pd.DataFrame(df1)

The desired output is like below - adding a "count" column to show the item count for all rows. Any suggestion is greatly appreciated.

enter image description here

CodePudding user response:

You could sum the number of values that are not "" row-wise (note that we subtract 1 here since "item" column doesn't contain empty spaces):

df1['count'] = df1.ne('').sum(axis=1) - 1

Output:

    item period1 period2 period3 period4  count
0  item1            4567    1234              2
1  item2            3333                      1
2  item3    5555            9993    2345      3
3  item4                                      0
  • Related