You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何编写自定义函数根据指定国家提取DataFrame对应行的账户名?

需求说明

编写pandas自定义函数,传入指定国家名称即可返回DataFrame中归属该国家的所有Account Name,预期调用形式为write_country("United States")时,返回所有所属国家为美国的账号名称。

测试数据集结构

测试数据集预览如下:

Rank    Account username    Account Name    Followers (millions)    Occupation  Country
0   1   @BarackObama    Barack Obama    132.0   44th President of the United States of America  United States
1   2   @justinbieber   Justin Bieber   114.2   Musician    Canada
2   3   @katyperry  Katy Perry  108.8   Musician    United States

原有实现问题

原有尝试代码如下:

entity=df.groupby([ "Country"])
b=df["Account Name"]
for items in zip(entity,b):
    print(items)

该实现存在两个核心问题:

  • groupby返回的是分组迭代对象,直接和单列Series做zip会出现类型不匹配,触发「布尔运算符不可迭代」报错
  • 逻辑没有对接函数入参做匹配筛选,即使不报错也无法实现按传入国家名返回对应账号的需求
正确实现代码

不需要使用groupby,直接用pandas布尔索引做筛选即可,逻辑简单执行效率更高:

import pandas as pd

def write_country(country_name: str, df: pd.DataFrame):
    # 筛选Country列和入参匹配的行,提取Account Name列返回
    return df.loc[df["Country"] == country_name, "Account Name"]

调用效果

基于给出的测试数据集,调用write_country("United States")返回结果:

0    Barack Obama
2       Katy Perry
Name: Account Name, dtype: object

如果需要返回原生Python列表格式而非pandas Series对象,将返回语句修改为return df.loc[df["Country"] == country_name, "Account Name"].tolist()即可,此时返回值为['Barack Obama', 'Katy Perry']。

内容的提问来源于stack exchange,提问作者hunny

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.29 08:24:16