为什么删除 Chunksize 时会出现错误?

问题描述 投票:0回答:1

我在运行 Python 代码时遇到错误,需要帮助来解决它。以下是详细内容:

import pandas as pd

df_list = []
file_path = 'houses.txt'

for chunk in pd.read_csv(file_path, chunksize=1000000, names=['Size()sqft', 'No of bedrooms', 'No of floors', 'Age of home', 'Price(1000s dollar)']):
    df_list.append(chunk)

df = pd.concat(df_list)

print(df_list)

输出:

0        952.0             2.0           1.0         65.0                271.5
1       1244.0             3.0           1.0         64.0                300.0
2       1947.0             3.0           2.0         17.0                509.8
3       1725.0             3.0           2.0         42.0                394.0
4       1959.0             3.0           2.0         15.0                540.0
..         ...             ...           ...          ...                  ...
95      1224.0             2.0           2.0         12.0                329.0
96      1432.0             2.0           1.0         43.0                388.0
97      1660.0             3.0           2.0         19.0                390.0
98      1212.0             3.0           1.0         20.0                356.0
99      1050.0             2.0           1.0         65.0                257.8

[100 rows x 5 columns]]

删除“chunksize”后。我收到此错误:

TypeError: cannot concatenate object of type '<class 'str'>'; only Series and DataFrame objs are valid

请解释一下问题是什么

python csv machine-learning
1个回答
0
投票

chunksize
是将
read_csv
的返回类型更改为您要迭代的
TextFileReader
对象。

chunksize:整数,可选
每个块从文件中读取的行数。传递一个值将导致函数返回一个 TextFileReader 对象进行迭代。有关迭代器和块大小的更多信息,请参阅 IO 工具文档。

当未指定

chunksize
时,它将返回
DataFrame

因此,您在该返回类型上迭代

for
循环的对象也会不同,并且
df_list
中的对象类型也会不同,最终导致在该列表上调用
pd.concat
时出现错误.

© www.soinside.com 2019 - 2024. All rights reserved.