我正在编写一个有 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"]
我似乎在堆栈上找不到任何关于在定义自己的函数时引用数据集中的列的内容。我尝试按照python的建议使用.items()
然后打印出来。从这里开始,我正在挣扎。AttributeError: 'DataFrame' object has no attribute 'item'
任何帮助将不胜感激。
使用DataFrame.loc
按列名过滤,如果location
列中只有一个country
,则输出是一个 eleemnt 系列,如果重复country
则Series
具有 2 个或更多值,如果不匹配country
,则输出Series
为空:
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')