简体   繁体   English

在 Pandas DataFrame 上应用函数

[英]Apply function over a Pandas DataFrame

I am working on Pandas and I am struggling to create a new column with information from an API over the rows of my dataframe.我正在研究 Pandas,我正在努力创建一个新列,其中包含来自数据帧行上的 API 的信息。

The "location" column I want to iterate is a Series of dictionaries like this:我要迭代的“位置”列是一系列这样的字典:

{'type': 'Point', 'coordinates': [-0.1394759, 51.5170385]}

My function:我的功能:

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()

How I am implementing the apply function (currently with a 'location', 'occurred at index 61' error):我是如何实现应用函数的(目前有一个'location', 'occurred at index 61'错误):

sample['testing'] = sample.apply(lambda x: starbucks(x["location"]), axis=1)

I've read some posts regarding the apply function and the documentation, but I am still missing something.我已经阅读了一些关于 apply 函数和文档的帖子,但我仍然缺少一些东西。

Help would be very much appreciated!非常感谢您的帮助!

Thanks谢谢

Your function is expecting a data frame, but you are passing a value to it.您的函数需要一个数据框,但您正在向它传递一个值。 I think your function should be:我认为你的功能应该是:

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

Here's another article that will give you more examples of how to use apply:这是另一篇文章,将为您提供有关如何使用 apply 的更多示例:
Pandas: How can I use the apply() function for a single column? Pandas:如何对单列使用 apply() 函数?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM