简体   繁体   中英

Function that when going through positive values in a row, it returns the column name, otherwise return the string “Not Available”

I need some help. I hope the below makes sense.

Imagine a dataframe with X number of rows and say 100 columns.

I want my function to arrange, in descending order, all the values in a given row. Then from those arranged values, give me the column-name of the first 10

Up to here, that is what the function below does for me.

def return_most_common_venues(row, 10):
    row_categories = row.iloc[1:]
    row_categories_sorted = row_categories.sort_values(ascending=False)

    return row_categories_sorted.index.values[0:10]

Additionally...

The problem that I have is when the row has less than 10 positive values. Meaning the remaining are zeros.

From those first 10 arranged values, say position 9 and 10 are zeros. I would like that instead of giving me the column-name for those zero values, I would like it to to return a string saying 'Not Available'.

How can I modify the above function to return what I need.

Thank you for your help!

You could replace them in the list

row_cat = row_categories_sorted.index.values[0:10]
replaced_row_cat = ['Not Available' if not c else c for c in row_cat]
return replaced_row_cat

Or simply,

new_cat=[]
for cat in row_categories_sorted.index.values[0:10]:
    if cat == 0:
        new_cat.append("Not available")
    else:
        new_cat.append(c)
return new_cat

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