Python 应用函数以在中创建多个列

Python 应用函数以在中创建多个列,python,pandas,apply,Python,Pandas,Apply,正如标题所示,我正在寻找一种方法,为数据框中的每一行应用一个函数,并针对一列创建多个新列 我的意思是,我有一个包含不同城市名称的df。现在我想创建两个新行,其中包含人口规模、国家、成立日期以及可能的更多信息 我有一个API,它将这些信息作为json返回。到现在为止,一直都还不错。 我目前正在做的是使用for循环遍历df,进行api调用,然后使用iloc设置列。。。这不是很好,也不是很有效率 我想知道是否可以使用apply/transform函数产生类似的结果 我当前的解决方案: for inde

正如标题所示,我正在寻找一种方法,为数据框中的每一行应用一个函数,并针对一列创建多个新列

我的意思是,我有一个包含不同城市名称的df。现在我想创建两个新行,其中包含人口规模、国家、成立日期以及可能的更多信息

我有一个API,它将这些信息作为json返回。到现在为止,一直都还不错。 我目前正在做的是使用for循环遍历df,进行api调用,然后使用iloc设置列。。。这不是很好,也不是很有效率

我想知道是否可以使用apply/transform函数产生类似的结果

我当前的解决方案:

for index, row in data.iterrows():
    print("--------------------->" + str(index))
    try:
        infos = cityInfo.download(row["city"],row["zip"])
    except:
        break
    if len(infos) == 0:
        print("City not found!")
    else:
        data["pop"].iloc[index] = infos["population"]
        data["country"].iloc[index] = infos["country"]
        data["founding"].iloc[index] = infos["foundingDate"

我很高兴得到任何帮助或提示

对于涉及API的问题,这里没有人能洞察到,不要指望有好的答案。在循环的每次迭代中调用API可能是最慢的部分。如果您的API不允许在一次调用中下载所有信息,那么您可能无法大幅提高性能。
此外,apply/transform(在接收行时)将执行基本相同的操作,调用API[行数]次。采用列,这些方法不会同时采用两列。

来自Pandas文档:

您不应该修改正在迭代的内容。这并不能保证在所有情况下都有效。根据数据类型,迭代器返回的是一个副本而不是一个视图,对其进行写入将没有任何效果

首先,我将迭代索引并引用该数据帧。(我没有写在您的try-except语句中,但如果需要,请添加它)

我假设您的API做了如下操作:

class cityInfoAPIDummy:
def __init__(self):
    self.data = pd.DataFrame(columns=["city","zip","population","country","foundingDate"],data=[["london","NE1","100000","UK","ages ago"],["birmingham","B","50000","UK","less long ago"]])
def download(self,city,z):
    return self.data[self.data["city"]==city][self.data["zip"]==z]
        
    
使用apply()函数执行所需操作的代码如下:

def get_info(city,z,field):
    cityInfo=cityInfoAPIDummy()

    infos = cityInfo.download(city,z)

    if len(infos)==0:
        print("City not found")
        return ""
    else:
        return infos[field].values[0]

if __name__ == "__main__":
    # assuming some dummy data in the format you were after
    data = pd.DataFrame(columns=["city","zip"],data=[["london","NE1"],["birmingham","B"]])
    data["pop"] = data.apply( lambda x: get_info(x["city"],x["zip"],"population") ,axis=1)
    data["country"] = data.apply(lambda x: get_info(x["city"],x["zip"],"country"),axis=1)
    data["founding"] = data.apply(lambda x: get_info(x["city"],x["zip"],"foundingDate"),axis=1)

print(data)

我希望这会有所帮助,但如果API是自定义API,则很难知道它为您提供了什么服务。

请给出一些复制输入和预期输出的最小示例。