Мой текущий код создает список строк (кортежей) для DataFrame и расширяет его с каждым пакетом новых строк. Затем он создает экземпляр Polars DataFrame из списка кортежей.
Текущий код
Код: Выделить всё
rows = []
def make_df(x):
for data in x: # This loops ~500k times
new_rows = process(data) # 4 new rows created
# new_rows is a tuple of length 4
# Each element (row) of the tuple is another tuple of length 10
rows.extend(new_rows)
return pl.DataFrame(rows, orient='row') # This line is very slow (4-5 sec)
Генератор (работает не быстрее)
Код: Выделить всё
def g(x):
for data in x: # This loops ~500k times
new_rows = process(data) # 4 new rows created
# new_rows is a tuple of length 4
# Each element of the tuple is another tuple of length 10
yield new_rows[0]
yield new_rows[1]
yield new_rows[2]
yield new_rows[3]
def make_df(x):
return pl.DataFrame(g(x), orient='row') # Slows down the loop by 5-6 seconds
Обновить
Воспроизводимый пример приведен ниже:
Код: Выделить всё
import polars as pl
import datetime
date = datetime.datetime(2024, 7, 14, 12, 30)
rows = []
def make_df():
for data in range(500000): # This loops ~500k times
new_row = (1, date, 3, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0, date)
new_rows = ((new_row),) * 4 # 4 new rows created
# new_rows is a tuple of length 4
# Each element (row) of the tuple is another tuple of length 10
rows.extend(new_rows)
return pl.DataFrame(
rows,
orient='row',
schema={
'a': pl.Int64,
'b': pl.Datetime,
'c': pl.Int64,
'd': pl.Float64,
'e': pl.Float64,
'f': pl.Float64,
'g': pl.Float64,
'h': pl.Float64,
'i': pl.Float64,
'j': pl.Datetime,
},
) # This line is very slow (4-5 sec)
make_df()
Похоже, что это замедление связано с созданием экземпляров столбцов datetime. Производительность в этом отношении значительно улучшилась, когда я обновил свои поляры с 1.17.1 до 1.20.0.
Подробнее здесь: https://stackoverflow.com/questions/793 ... hat-return