如何将大型 CSV 加载到 Python 中,选择特定列并另存为新 CSV?

我有一个 CSV 文件,大约有 800 万行,大小约为 3gb。我有一个要保存到新 CSV 中的特定列的列表。我一直在尝试将 Panda 与 Python 结合使用,但我就是做不好。


这是我一直在使用的代码:


import pandas as pd

df = pd.read_csv('MyFile.csv' , usecols = ['AAA','BBB','CCC',])

在最后一条命令之后,终端行返回 3 个点,如“...”。然后我尝试输入这个命令


df.to_csv('NewFile.csv', index=False)

但我收到以下错误:


file "<stdin>", line 2

  df.to_csv('NewFile.csv', index=False)

   ^

SyntaxError: invalid syntax


任何帮助将不胜感激。谢谢你。


编辑:这就是整个终端屏幕文本。


Python 3.7.6 (default, Jan  8 2020, 20:23:39) [MSC v.1916 64 bit (AMD64)] :: Anaconda, Inc. on win32

Type "help", "copyright", "credits" or "license" for more information.

>>> df=pd.read_csv('MyFile.csv' , usecols = ['AAA','BBB','CCC',]

... pd.df.to_csv('NewFile.csv', index=False)?

  File "<stdin>", line 2

    pd.df.to_csv('NewFile.csv', index=False)?

     ^

SyntaxError: invalid syntax

>>>


慕盖茨4494581
浏览 136回答 4
4回答

冉冉说

你有语法错误,因为你没有关闭终端下一行的括号>>>&nbsp;df=pd.read_csv('MyFile.csv'&nbsp;,&nbsp;usecols&nbsp;=&nbsp;['AAA','BBB','CCC',]

慕勒3428872

将 3GB 的文件读入内存不是一个好主意(这就是 pandas 会做的)。我建议使用流式传输工具,例如awk先过滤您的数据。

MM们

您是否尝试过类似的东西:df.to_csv&nbsp;(r'C:\Users\Ron\Desktop\NewFile.csv',&nbsp;index&nbsp;=&nbsp;False)替换C:\Users\Ron\Desktop\NewFile.csv为输出文件名。

繁星淼淼

我找到了这个解决方案。我找到了一个代码来删除我不想要的列。所以复制了 CSV 并做到了。这是我使用的 Py 文件:import csvinput_file = 'input.csv'output_file = 'output.csv'cols_to_remove = [1, 4, 10, 11] # Column indexes to be removed (starts at 0)cols_to_remove = sorted(cols_to_remove, reverse=True) # Reverse so we remove from&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; the end firstrow_count = 0 # Current amount of rows processedwith open(input_file, "r") as source:reader = csv.reader(source)with open(output_file, "w", newline='') as result:&nbsp; &nbsp; writer = csv.writer(result)&nbsp; &nbsp; for row in reader:&nbsp; &nbsp; &nbsp; &nbsp; row_count += 1&nbsp; &nbsp; &nbsp; &nbsp; print('\r{0}'.format(row_count), end='') # Print rows processed&nbsp; &nbsp; &nbsp; &nbsp; for col_index in cols_to_remove:&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; del row[col_index]&nbsp; &nbsp; &nbsp; &nbsp; writer.writerow(row)
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python