我正在編寫一個有 3 個參數的函數: country_metric(df, country, column)這是[參數]單獨的功能。df- 數據框country- 一個字符串(可以假設是一個條目,可以在名為 的列中找到location)column- 一個字符串(可以假定為一列(位置除外),可在df該函數應返回給定國家/地區的行和根據第二個字符串標記的列的值:我的功能不起作用,因為我不知道如何正確表達該功能。這是我到目前為止所擁有的:def country_metric(df, country,column): for column in df: if df["location"] == country: return df[df["location"] == country]["column"]我似乎無法在堆棧上找到任何有關在定義自己的函數時引用數據集中的列的信息。我嘗試.items()按照 python 的建議使用,然后打印出來。從現在開始我就在掙扎。 AttributeError: 'DataFrame' object has no attribute 'item'任何幫助,將不勝感激。
1 回答

茅侃侃
TA貢獻1842條經驗 獲得超21個贊
與按列名稱過濾器一起使用,如果列中DataFrame.loc
只有一個,則輸出是一個元素系列,如果重復,則輸出為 2 個或多個值,如果不匹配,則輸出為空:country
location
Series
country
Series
country
def?country_metric(df,?country,column): ????return?df.loc[df["location"]?==?country,?column]
如果需要第一個匹配值,如果沒有匹配,則沒有錯誤,country
請使用iter
技巧next
:
def?country_metric(df,?country,column): ????return?iter(next(df.loc[df["location"]?==?country,?column]),?'no?match')
添加回答
舉報
0/150
提交
取消