为什么在使用 Python Pandas 数据框删除重复项后我的 csv 文件更大

问题描述

我编写此代码是为了消除大型 (800000) 推文 csv 文件中的重复项,但是当我运行它时,我得到的文件比原始文件大:原始文件为 1,580,307 KB,生成文件为 1,852,462知识库。我尝试了 20 行中较小的一行,原始文件为 45KB,在这种情况下我得到的结果文件为 46KB。如果有人可以指导我如何发生这种情况或我做错了什么,我将不胜感激。我卡住了!

import csv 
import pandas as pd


geofile_input = r'GeoFile_20tweets.csv'
geofile_output = 'GeoFile_20tweets_output.csv'

file1= open(geofile_input,encoding="utf8")
reader1 = csv.reader(file1)
lines_in =len(list(reader1))
print('row_count csv input file: ',lines_in)

print('start reading the file on pandas')
df = pd.read_csv(geofile_input,sep=',')

print('dataframe',df.dtypes)

print('droping duplicates in pandas')
df.drop_duplicates(subset=None,keep='first',inplace=True)


print('saving the data frame in csv without duplicates')
df.to_csv(geofile_output,index=False,',header=True)

print('counting rows for the csv output')
file2= open(geofile_output,encoding="utf8")
reader2 = csv.reader(file2)
lines_out =len(list(reader2))

print('row_count csv output file: ',lines_out)
print('Process completed!')

解决方法

演示数据

cmd = '''
cat > test.csv << 'EOF'
a,b,c,d
1,2,1,1
1,1.0,1
EOF
'''

pycmd = lambda cmd: get_ipython().system(cmd)
pycmd(cmd)

df = pd.read_csv('test.csv')
df.to_csv('test_1.csv',index=False)

# -rw-r--r--. 1 root     88 Jan 20 16:16 test_1.csv
# -rw-r--r--. 1 root     74 Jan 20 16:15 test.csv

!cat test_1.csv
a,1