大熊猫数据框早期数据输入

时间:2020-02-27 23:21:56

标签: python pandas dataframe memory types

我正在尝试从数据库中加载相对大量的数据,我想在开始加载之前通过分配适当的数据类型来优化我的数据框。但是到目前为止,我发现只有在加载数据框后才能优化数据类型,并且可以从下面的代码中看到这种情况。因此,如果还有其他方法可以尽早分配数据类型,那将真正帮助我管理代码的内存需求。

dbdf = pd.DataFrame(columns=['ID', 'Incr', 'Found'])
dbdf = dbdf.astype({'ID': str, 'Incr': np.int16, 'Found': str})

dbdf = pd.read_sql(
    'SELECT substring_index(ID, \'.\', 2) as ID, Incr, \'Y\' as Found FROM database.',
    conn, coerce_float=True)  # database dataframe

print('$$$$$BEFORE$$$$$')
print(dbdf.memory_usage())
print(dbdf.dtypes)

print('$$$$$AFTER$$$$$')
dbdf = dbdf.astype({'ID': np.float64, 'Incr': np.int16, 'Found': str})
print(dbdf.memory_usage())
print(dbdf.dtypes)

以下是结果

$$$$$BEFORE$$$$$
ID        6695328
Incr    6695328
Found      6695328
dtype: int64
ID        object
Incr     int64
found      object

$$$$$AFTER$$$$$
ID        6695328
Incr    1673832
Found      6695328
dtype: int64
ID        float64
Incr      int16
Found       object

1 个答案:

答案 0 :(得分:0)

如果要在加载之前指定列的类型,则有两个选项(据我所知:P)。

  1. 在读取sql数据时,使用cast指定列的类型。 (我对sql不了解,所以我不确定语法,对此感到抱歉)

'SELECT cast (ID as float64()), cast (Incr as int()) FROM database'

refer the link

  1. 使用dtype参数指定列的类型。

pd.read_csv('file.csv', dtype={'ID': str, 'Incr': np.int16, 'Found': str}, conn, coerce_float=True)

希望它会有所帮助:)