我正在编写一个代码,我需要根据大表的每一行填充一组数据结构。现在,我正在使用 pandas 来读取数据并进行一些基本的数据验证预处理。但是,当我进入流程的其余部分并将数据放入相应的数据结构中时,完成循环并填充我的数据结构需要相当长的时间。例如,在下面的代码中,我有一个包含 15 M 记录的表。表有三列,我基于每一行创建一个 foo() 对象并将其添加到列表中。
# Profile.csv
# Index | Name | Family| DB
# ---------|------|-------|----------
# 0. | Jane | Doe | 08/23/1977
# ...
# 15000000 | Jhon | Doe | 01/01/2000
class foo():
def __init__(self, name, last, bd):
self.name = name
self.last = last
self.bd = bd
def populate(row, my_list):
my_list.append(foo(*row))
# reading the csv file and formatting the date column
df = pd.read_csv('Profile.csv')
df['DB'] = pd.to_datetime(df['DB'],'%Y-%m-%d')
# using apply to create an foo() object and add it to the list
my_list = []
gf.apply(populate, axis=1, args=(my_list,))
因此,在使用 pandas 将字符串日期转换为日期对象之后,我只需要遍历 DataFrame 来创建我的对象并将它们添加到列表中。这个过程非常耗时(在我的真实示例中,它甚至需要更多时间,因为我的数据结构更复杂并且我有更多列)。所以,我想知道在这种情况下提高我的运行时间的最佳做法是什么。我什至应该用它pandas
来阅读我的大表并逐行处理它们吗?