Skip to main content
 首页 » 编程设计

python之Pandas iloc 不返回数据切片

2025年01月19日9cmt

我正在尝试拆分包含 1500 多家公司股票数据的 CSV 文件。第一列包含日期,后续列包含公司数据。

当我使用 iloc 功能将 CSV 文件拆分为包含较少列的较小文件时,它会生成一个更大的文件。

数据如下所示。

import pandas as pd 
 
csv_path = "new-data.csv" 
filename = 1 
out_path = "C:\\Users\\ThirdHandBD\\Desktop\\Data Splitting\\pd-split\\" + str(filename) + ".csv" 
 
#column increment 
x = 30 * 59 
 
'''for index, row in df.itertuples(): 
    if index == ((x * filename) + 1): 
        pd.read_csv(csv_path).iloc[:, :index].to_csv(out_path) 
        filename += 1''' 
 
pd.read_csv(csv_path, skiprows = 1, dtype='unicode').iloc[:, :1].to_csv(out_path) 

新文件比原始文件大。

没有抛出错误,dtype 设置为 unicode 以解决低内存错误。文件大小约为 300 MB,类似的数据类型适用于具有类似文件大小的其他文件。 Skiprows 设置为 1,因为第一行是空的。

我做错了什么?

编辑:

这就是新数据的样子。它添加了一堆逗号,然后其余数据相同。我该如何解决这个问题?

编辑 x 2:

在考虑了 mightpile 的建议后,我去掉了第 6 行标题以外的所有内容,并使用文本编辑器减少了行数。然后我运行以下代码。

import pandas as pd 
 
csv_path = "C:\\Users\\ThirdHandBD\\Desktop\\Data Splitting\\pd-split\\small-data.csv" 
out_path = "C:\\Users\\ThirdHandBD\\Desktop\\Data Splitting\\pd-split\\1.csv" 
 
df = pd.read_csv(csv_path, header=0, dtype='unicode') 
print("I read in a dataframe with {} columns and {} rows.".format( 
len(df.columns), len(df) 
)) 
 
out_df = df.iloc[:, :1] 
out_df.to_csv(out_path) 
# This should be the same as df, but with only the first column. 
# Check it with similar code to above. 

结果

我读入了一个包含 1546 列和 13 行的数据框。

它只会剪切随机数量的列标题。当我运行第一列和最后一列的 mightypile 代码时,我返回了随机 header 。我的 csv 没有被正确读取,我不明白为什么。

print("The first and last columns are:") 
print(df.head(1)) 
print(df.tail(1)) 

终端输出:

相同的终端输出不断重复。抱歉我是个愚蠢的人,但我觉得我在倒退而不是进步。

请您参考如下方法:

有几个问题。您输入的 csv 与第 6 行相比,第 0-5 行的格式完全不同。前 6 行的结构不像具有行和列的 DataFrame。如果您需要这些数据,您可能需要编写一些自定义代码来提取它们。

第二个建议是使用文本编辑器(谷歌搜索建议,但这些不是 Word、Excel 或 Writepad)来保存一小部分数据以供试验。试图找出如何用 300MB 的怪物读取 csv 文件会给你带来很多痛苦和浪费时间。

从 6 开始,您的部分图像看起来更像 DataFrame,列标题位于第 6 行,数据超出该行。但是无法从您的图像中判断出有多少列。所以,首先,忽略文件顶部更复杂的结构,看看你是否能从一个文件的其余部分弄清楚你正在读取什么,以及你是否在写你认为的东西。一旦您在单个文件上采用您的方法,您就可以开始迭代更多文件。

import pandas as pd 
 
csv_path = "new-data.csv" 
out_path = "C:\\Users\\ThirdHandBD\\Desktop\\Data Splitting\\pd-split\\1.csv" 
 
df = pd.read_csv(csv_path, header=6, dtype='unicode') 
print("I read in a dataframe with {} columns and {} rows.".format( 
    len(df), len(df.columns) 
)) 
print("The first 4 and last 4 columns are:") 
print(df.head(4)) 
print(df.tail(4)) 
 
out_df = df.iloc[:, :1] 
# This should be the same as df, but with only the first column. 
# Check it with similar code to above. 

如果您的行仍然太大而无法使用 .head() 和 .tail() 函数进行可视化,我会再次敦促您从“玩具”数据集开始,以便您可以直观地了解代码的作用为你。对于大数据来说,这既困难又令人沮丧。