You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何将API返回的字节字符串转换为Pandas DataFrame?

问题描述

我调用API后得到如下响应:

print(res)

b'amp,dev, util\n192.168.101.1,server123,80%\n192.168.101.4,serverabc,75%\n192.68.101.5,serverusa1,50%\n'

想要将其转换成如下格式的DataFrame:

Amp.          dev.      util
192.168.101.1 server123  80%
192.168.101.4 serverabc  75%
192.168.101.5 serverusa1 50%

尝试了以下代码:

import pandas as pd
pd.read_table(res, sep='\n')

但出现错误:OSError: expected file path,请问哪里操作错了?

错误原因

pd.read_table() 方法的第一个参数要求是文件路径字符串或者类文件对象,你直接传入了API返回的字节字符串res,不符合参数要求,因此触发报错。

解决方案
  • 先将字节字符串解码为普通字符串
  • 使用io.StringIO把字符串包装成类文件对象,让pandas可以像读取文件一样读取它
  • 由于你的数据是逗号分隔格式,用pd.read_csv()比read_table()更适配,同时可以直接重命名列名

完整代码示例:

import pandas as pd
from io import StringIO

# 解码字节字符串为UTF-8格式的普通字符串
res_str = res.decode('utf-8')
# 将字符串转为类文件对象
data_stream = StringIO(res_str)
# 读取为DataFrame,指定分隔符、表头位置并自定义列名
df = pd.read_csv(data_stream, sep=',', header=0, names=['Amp.', 'dev.', 'util'])
# 打印结果
print(df)

执行后就能得到目标格式的DataFrame。

内容的提问来源于stack exchange,提问作者user1471980

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.30 20:55:06