我在正确读取此来源的数据时遇到一个小问题。我试着写:
path = 'http://archive.ics.uci.edu/ml/machine-learning-databases/image/segmentation.data'
df = pd.read_table(path)
然后我写道:
df = pd.read_table(path, sep=',', header=None)
出现错误:
ParserError: Error tokenizing data. C error: Expected 1 fields in line 4, saw 19
您能帮我找到解决方案吗?
该文件基本上是一个
csv
文件,因此您可以使用 read_csv
。与 skiprows=2
结合使用可跳过文件中前一个不相关的行。
import pandas as pd
path = 'http://archive.ics.uci.edu/ml/machine-learning-databases/image/segmentation.data'
df = pd.read_csv(path, skiprows=2, index_col=False)
输出
df.head()
:
区域-质心-COL | 区域-质心-行 | 区域像素数 | 短线密度-5 | 短线密度-2 | 边缘平均 | VEDGE-SD | 对冲均值 | 对冲-SD | 强度平均值 | RAWRED-MEAN | RAWBLUE-MEAN | RAW绿色平均 | EXRED-平均值 | EXBLUE-MEAN | EXGREEN-Mean | 价值均值 | 饱和度平均值 | 色相均值 | |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
0 | 砖脸 | 140 | 125 | 9 | 0 | 0 | 0.277778 | 0.062963 | 0.666667 | 0.311111 | 6.18518 | 7.33333 | 7.66667 | 3.55556 | 3.44444 | 4.44444 | -7.88889 | 7.77778 | 0.545635 |
1 | 砖脸 | 188 | 133 | 9 | 0 | 0 | 0.333333 | 0.266667 | 0.5 | 0.0777777 | 6.66667 | 8.33333 | 7.77778 | 3.88889 | 5 | 3.33333 | -8.33333 | 8.44444 | 0.53858 |
2 | 砖脸 | 105 | 139 | 9 | 0 | 0 | 0.277778 | 0.107407 | 0.833333 | 0.522222 | 6.11111 | 7.55556 | 7.22222 | 3.55556 | 4.33333 | 3.33333 | -7.66667 | 7.55556 | 0.532628 |
3 | 砖脸 | 34 | 137 | 9 | 0 | 0 | 0.5 | 0.166667 | 1.11111 | 0.474074 | 5.85185 | 7.77778 | 6.44444 | 3.33333 | 5.77778 | 1.77778 | -7.55556 | 7.77778 | 0.573633 |
4 | 砖脸 | 39 | 111 | 9 | 0 | 0 | 0.722222 | 0.374074 | 0.888889 | 0.429629 | 6.03704 | 7 | 7.66667 | 3.44444 | 2.88889 | 4.88889 | -7.77778 | 7.88889 | 0.562919 |
你能给出这样的编码吗:
path = 'http://archive.ics.uci.edu/ml/machine-learning-databases/image/segmentation.data'
df = pd.read_csv(path,encoding = 'utf8')
如果不行,可以尝试其他编码吗?
问题似乎是数据文件包含一些 Pandas 无法解析的元信息。您需要将文件转换为 CSV,然后才能被
pandas
读取。
为此,请首先将文件下载到本地计算机的某个位置
filepath
并删除以 ;;;
开头的行和空行。然后运行 pd.read_table(filepath, sep='\t')
或 pd.read_csv(filepath)
应该可以按预期工作。
请注意,
header
参数并不引用文件可能包含的任何通用标头信息。 header
让 pandas
知道 CSV 中的第一行是否包含列名称(如果 header
为 True
),或者文件中的实际数据是否从第一行开始(如果 header
为False
)。
现在没有手动下载,因为存储库提供了其Python API:
pip install ucimlrepo
例如,使用著名的“联合循环发电厂”数据: https://archive.ics.uci.edu/dataset/294/combined+cycle+power+plant
from ucimlrepo import fetch_ucirepo
# fetch dataset
combined_cycle_power_plant = fetch_ucirepo(id=294)
# data (as pandas dataframes)
X = combined_cycle_power_plant.data.features
y = combined_cycle_power_plant.data.targets
# metadata
print(combined_cycle_power_plant.metadata)
# variable information
print(combined_cycle_power_plant.variables)