Pandas iloc没有返回数据切片

时间:2018-04-25 22:20:28

标签: python pandas

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

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

以下是数据的样子。

enter image description here

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)

新文件比原始文件大。

enter image description here

没有抛出错误,dtype设置为unicode以绕过低内存错误。文件大小约为300 MB,类似的dtypes适用于具有相似文件大小的其他dtypes。由于第一行为空,因此将Skiprows设置为1。

我做错了什么?

修改

enter image description here

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

编辑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.

RESULT

我在数据框中读取了1546列和13行。

enter image description here

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

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

TERMINAL OUT:

enter image description here

相同的终端输出重复打开和打开。对不起是一个愚蠢的人,但我觉得我要退步而不是取得进步。

1 个答案:

答案 0 :(得分:1)

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

第二个建议是使用文本编辑器(google获取建议,但这些不是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()函数进行可视化,我会再次建议您从“玩具”数据集开始,以便您可以直观了解代码正在执行的操作为了你。对于大数据而言,这是艰难而令人沮丧的。

相关问题