以pandas dataframe的形式读取url(python3)

2024-10-01 04:46:06 发布

您现在位置:Python中文网/ 问答频道 /正文

我读了几个关于这个话题的问题,但似乎没有什么对我有用。在

我想从这个页面“http://archive.ics.uci.edu/ml/machine-learning-databases/statlog/heart/heart.dat”检索数据,并为列指定特定的名称。在

我的代码如下所示,这不允许我为数据的列指定名称,因为所有内容都在一列中:

import pandas as pd
import io
import requests
url="http://archive.ics.uci.edu/ml/machine-learningdatabases/statlog/heart/heart.dat"
s=requests.get(url).content
header_row = ['age','sex','chestpain','restBP','chol','sugar','ecg','maxhr','angina','dep','exercise','fluor','thal','diagnosis']
c=pd.read_csv(io.StringIO(s.decode('utf-8')), names=header_row)
print(c)

输出为:

^{pr2}$

我要做什么才能实现我的目标?在

非常感谢!!!在


Tags: 数据import名称httpmachinemldatabasedat
1条回答
网友
1楼 · 发布于 2024-10-01 04:46:06

您提供的链接缺少连字符。我已经在我的回答中更正了这一点。基本上,您需要将s字符串解码为utf-8,然后在\n上拆分它以获得每一行,然后在空白处拆分每一行以分别获得每个值。这将为您提供数据集的嵌套列表表示形式,您可以将其转换为pandas数据帧,然后可以分配列名。在

import pandas as pd
import io
import requests
url = "https://archive.ics.uci.edu/ml/machine-learning-databases/statlog/heart/heart.dat"
s = requests.get(url).content
s = s.decode('utf-8')
s_rows = s.split('\n')
s_rows_cols = [each.split() for each in s_rows]
header_row = ['age','sex','chestpain','restBP','chol','sugar','ecg','maxhr','angina','dep','exercise','fluor','thal','diagnosis']
c = pd.DataFrame(s_rows_cols, columns = header_row)
c.head()

相关问题 更多 >