在Python中处理大型CSV文件

qgzx9mmu  于 5个月前  发布在  Python
关注(0)|答案(2)|浏览(87)

第一次使用python,我想知道是否有一种方法可以加速处理我的CSV文件。
基本上,我使用Pandas读取CSV文件,每行都有一些需要做的事情。
代码给出了我想要的结果,但是我认为它运行的时间太长了。在我的测试CSV上运行1000行需要40秒,在10000行的情况下需要400秒,但是我必须在包含超过一百万行的CSV中运行它。
我将在下面添加一个伪代码:

import os
import pandas as pd

desktop = os.path.join(os.path.join(os.environ["USERPROFILE"]), "Desktop")
dados = pd.read_csv(desktop + '\\test-1000-rows.csv')
for i, row in dados.iterrows():
    #for each item in a list
       #check if row[column_a] or row[column_b] has the item as value
          #add row[column_c] to a list if true

字符串
有什么方法可以加快这个过程吗?我是不是用错了pandas?

yyyllmsg

yyyllmsg1#

乍看之下,危险信号是iterrows()。在大多数情况下,您应该避免使用iterrows()和apply(),因为它们速度很慢,而且会占用大量时间。请参阅Does pandas iterrows have performance issues?
Pandas可以快速地对列执行操作,所以你应该尽可能多地尝试使用向量化操作。

'''
# An example of a vectorized operation
df['new_column'] = df['existing_column'] + 1
'''

字符串
我会从这里开始。如果你仍然对速度不满意,你可以看看其他的解决方案,比如“chunksize”来以更小的块读取CSV。

3htmauhk

3htmauhk2#

这个怎么样?

# vectorized operations to check for the items in column_a and column_b
mask = dados['column_a'].isin(items_to_check) | dados['column_b'].isin(items_to_check)

# extract the values from column_c where the condition is True
selected_values = dados.loc[mask, 'column_c'].tolist()

字符串

相关问题