Python 在数据帧上应用函数

Python 在数据帧上应用函数,python,pandas,dataframe,apply,Python,Pandas,Dataframe,Apply,我正在研究Pandas,我正在努力创建一个新的列,其中包含来自API的信息,这些信息位于我的数据帧的行上 我要迭代的“location”列是一系列字典,如下所示: {'type': 'Point', 'coordinates': [-0.1394759, 51.5170385]} 我的职能: def starbucks(df): API_key = os.getenv('API_KEY') lat = list(df["location"])[1]["coordinates"]

我正在研究Pandas,我正在努力创建一个新的列,其中包含来自API的信息,这些信息位于我的数据帧的行上

我要迭代的“location”列是一系列字典,如下所示:

{'type': 'Point', 'coordinates': [-0.1394759, 51.5170385]}
我的职能:

def starbucks(df):
    API_key = os.getenv('API_KEY')
    lat = list(df["location"])[1]["coordinates"][1]
    lon = list(df["location"])[1]["coordinates"][0]
    base_url = "https://maps.googleapis.com/maps/api/place/textsearch/json?"
    endpoint = "query=starbucks&location={0},{1}&radius=1000&key={2}".format(lat, lon, API_key)
    res = requests.get(base_url+endpoint).json()
我是如何实现apply函数的(当前有一个
'location','发生在索引61'
错误):

我已经阅读了一些关于apply函数和文档的帖子,但是我仍然缺少一些东西

非常感谢您的帮助


谢谢

您的函数需要一个数据帧,但您正在向它传递一个值。我认为你的职能应该是:

def starbucks(val):
    API_key = os.getenv('API_KEY')
    lat = list(val)[1]["coordinates"][1]
    lon = list(val)[1]["coordinates"][0]
    base_url = "https://maps.googleapis.com/maps/api/place/textsearch/json?"
    endpoint = "query=starbucks&location={0},{1}&radius=1000&key={2}".format(lat, lon, API_key)
    res = requests.get(base_url+endpoint).json()
    return res
下面的另一篇文章将为您提供更多如何使用apply的示例:

这是否回答了您的问题?为什么要将列强制转换为列表
我要迭代的“location”列是一系列字典,如下所示:
为什么不将数据分成多个列?
def starbucks(val):
    API_key = os.getenv('API_KEY')
    lat = list(val)[1]["coordinates"][1]
    lon = list(val)[1]["coordinates"][0]
    base_url = "https://maps.googleapis.com/maps/api/place/textsearch/json?"
    endpoint = "query=starbucks&location={0},{1}&radius=1000&key={2}".format(lat, lon, API_key)
    res = requests.get(base_url+endpoint).json()
    return res