python - `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)
解决方案
你的query
函数需要一个参数
当您调用apply
函数时,您收到的是 apandas series
并且基于您的axis
参数的值您得到row
or column
。axis
当您设置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
推荐阅读
- c# - 如何在ajax post上使用jquery验证模型绑定表单?
- docker - 我如何在两个 docker 容器上使用或映射相同的端口
- haskell - 如何为不是变压器的 monad 定义 MonadBaseControl?
- swift - 有没有办法让浮动区域让我们可以在 Xcode 上的多个屏幕上工作?
- c++ - 我是否需要释放使用“new”时分配的 wchar 内存,还是 delete[] 也释放它?
- mysql - 优化 SQL 查询 - 从第二个表中包含多行的两个表中获取记录
- wordpress - 现有安装上的 WP-CLI?
- amazon-dynamodb - VelocityTemplate,生成开始和结束日期之间的日期列表
- docker - 为什么容器在 CMD ( docker ) 中启动后不启动?
- javascript - 消息:未初始化的字符串偏移量:0,同时插入动态输入字段数据