[英]how to type a function that returns None if input is string otherwise return the input as is
[英]Function that when going through positive values in a row, it returns the column name, otherwise return the string “Not Available”
我需要一些幫助。 我希望以下內容有意義。
想象一個 dataframe 有 X 行,說 100 列。
我希望我的 function 按降序排列給定行中的所有值。 然后從這些排列的值中,給我前 10 個的列名
到這里為止,這就是下面的 function 為我所做的。
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]
此外...
我遇到的問題是該行的正值少於 10 個。 意思是剩下的都是零。
從前 10 個排列的值中,例如 position 9 和 10 為零。 我希望這樣,而不是給我那些零值的列名,我希望它返回一個字符串,說“不可用”。
如何修改上述 function 以返回我需要的內容。
謝謝您的幫助!
您可以在列表中替換它們
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
或者簡單地說,
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
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.