0

My Dataframe: billboard_2 enter image description here

I need to count the number of weeks a song is on billboards by using an apply function and a simple python function. But apparently, I am not able to do so.

I managed to do it via the lambda function but I am supposed to use apply function. The output I am getting lambda function is exactly what I need using the normal function.

WeeklyRating = billboard_2.apply(lambda x : x.count()-1, axis=1)

WeeklyRating

Output using lambda function enter image description here

I tried converting that lambda function to a normal function but each time I am getting some error. Following is what I tried and I got an error saying - 'Series' object has no attribute 'iterrows'.

def bill_week(val):
    for i, row in val.iterrows():
        return(row.count()-1)

billboard_2.apply(bill_week)

I guess what I am asking is how do I convert that lambda function to a normal function.

Shubham Sharma
  • 68,127
  • 6
  • 24
  • 53
Myst
  • 3
  • 2
  • Welcome to Stackoverflow. Please [don't post images of code/data](https://meta.stackoverflow.com/questions/285551/why-not-upload-images-of-code-errors-when-asking-a-question) instead add them in text format so that we could be able to copy these while trying to answer your question. Please take some time to read [How to ask good pandas questions?](https://stackoverflow.com/questions/20109391/how-to-make-good-reproducible-pandas-examples) – Shubham Sharma Apr 28 '21 at 07:49
  • Thanks for letting me know good sir, I will read through the post and make sure I ask a formatted question next time. – Myst Apr 28 '21 at 07:55
  • There is no need to use `apply` or `iterrows` here, you can simply count the `non-NaN` values using a vectorized function. Please check `billboard_2.drop('track', axis=1).count(axis=1)` – Shubham Sharma Apr 28 '21 at 08:00
  • I think this will be helpul: https://stackoverflow.com/questions/30059260/python-pandas-counting-the-number-of-missing-nan-in-each-row – sagmansercan Apr 28 '21 at 08:33

1 Answers1

0

count(axis=1) let alone gives no. of non-na values in a row

billboard_2.count(axis=1)

If you want to use .apply

def count_non_na(x):
    return x.isna().sum()

billboard_2.apply(count_non_na, axis=1)

In combination with lambda

billboard_2.apply(lambda x: x.isna().sum(), axis=1)
imdevskp
  • 2,103
  • 2
  • 9
  • 23