首页 > 解决方案 > `NameError: name column_name 未定义`

问题描述

数据框

   uid,api_url
    1, abc.com
    2, xyz.com

代码

def query():
    jso = {"id": uid,"docs": {"doc1":api_url,"type": "US","advanced": {"details":true}}} 
    json_d = json_dumps(jso)
    headers = {"Content-Type": "application/json"}
    response = requests.post("https://example.net/document",headers=headers,json=json_d)
    return response.text

适用于df df['res'] = df[['uid','api_url']].apply(query(),axis = 1)

NameError: name 'uid' is not defined

下面的查询在应用于变量和硬编码时工作正常ui_id:'random_number'

def query_api(api_url):
    headers = {"Content-Type": "application/json"}
    json_d = {'ui_id': '1111', 'data': {'url': api_url}}
    response = requests.post("http://example.net/v3/doc", 
                             headers=headers, json=json_d)
    return response.text

df['res1'] = df['api_url'].apply(query_api)

标签: pythonpandas

解决方案


你的query函数需要一个参数

当您调用apply函数时,您收到的是 apandas series并且基于您的axis参数的值您得到rowor columnaxis当您设置to的值时,1您会得到一行。

所以当你打电话

df['res'] = df[['uid','api_url']].apply(query, axis = 1)

您将数据框的每一行作为查询函数的参数。

所以你需要修改你的query功能

def query(x):
    jso = {"id": x.uid,"docs": {"doc1":x.api_url,"type": "US","advanced": {"details":true}}} 
    json_d = json_dumps(jso)
    headers = {"Content-Type": "application/json"}
    response = requests.post("https://example.net/document",headers=headers,json=json_d)
    return response.text

您的第二种情况query_api有效,因为它有一个参数,它将成为您的数据框的列。

希望这个解释有所帮助。

附言

在你的第一个apply电话中,你有query()作为论据。我认为那是一个错字。您只需要指定函数的名称。

编辑

我添加了一个示例以进一步解释

>>> df
   uid  api_url
0    1  abc.com
1    2  xyz.com

>>> def query(x):
...     return str(x.uid) + x.api_url

>>> df.apply(query, axis =1)
0    1abc.com
1    2xyz.com
dtype: object

推荐阅读