我有一个 FastAPIGET端点,它返回大量 JSON 数据(约 160,000 行和 45 列)。毫不奇怪,使用返回数据非常json.dumps()慢。我首先使用文件中的数据读取数据json.loads(),并根据输入的参数对其进行过滤。有没有比使用更快的方法将数据返回给用户return data?以目前的状态,需要将近一分钟的时间。
我的代码目前如下所示:
# helper function to parse parquet file (where data is stored)
def parse_parquet(file_path):
df = pd.read_parquet(file_path)
result = df.to_json(orient = 'records')
parsed = json.loads(result)
return parsed
@app.get('/endpoint')
# has several more parameters
async def some_function(year = int | None = None, id = str | None = None):
if year is None:
data = parse_parquet(f'path/{year}_data.parquet')
# no year
if year is …Run Code Online (Sandbox Code Playgroud) 我正在尝试创建一个简单的函数,它将接受消息(字符串)并将其传递给openai.ChatCompletion.create(),但是当我使用 F 字符串时,它会返回一个对象错误。对调试Python不太熟悉,所以我有点卡在这里。
def get_response(message):
response = openai.ChatCompletion.create(
model = 'gpt-3.5-turbo',
temperature = 1,
messages = [
f"{{'role': 'user', 'content': '{message}'}}"
]
)
return response.choices[0]["message"]["content"]
# get_response('What is 2 + 2?')
Run Code Online (Sandbox Code Playgroud)
它返回:
InvalidRequestError: "{'role': 'user', 'content': 'What is 2 + 2?'}" is not of type 'object' - 'messages.0'
Run Code Online (Sandbox Code Playgroud)
我想我可能需要将字符串转换为openai已创建的某个独特的类,但我不太确定如何执行。查看了源代码,但找不到对该类的引用。
这可能是一个深奥的问题或用例,但是filter当列名和值位于向量内部时,是否有快速获取 tibble 的方法?
假设我想过滤mpg和。我可以做类似的事情:hpmtcars
filter(mtcars, mpg >= 15 & hp >= 100)
Run Code Online (Sandbox Code Playgroud)
相反,假设我有几种过滤情况——其中要在一个向量中过滤列,而在另一个向量中过滤值。(实际上,我可能在一个较大的 df 中有四到五个案例。)
car_stat <- c('mpg', 'hp')
car_value <- c(15, 100)
Run Code Online (Sandbox Code Playgroud)
显然这是行不通的。
filter(mtcars, car_stat >= car_value)
Run Code Online (Sandbox Code Playgroud)
但是是否有一些简洁的dplyr/tidyverse方法来使用向量进行过滤,或者我是否愿意使用某些循环将其分解为单独的向量,每个向量的长度为一?