Как заставить типы данных с помощью функции pandas построителя DataFrame from_records? - PullRequest
0 голосов
/ 25 февраля 2020

Когда я строю pandas DataFrame из списка ndarrays типа float32, я получаю pandas DataFrame с элементами float64.

Как получить элементы float32 в кадре данных?

       import numpy as np
       import pandas as pd

       # Create 2 dummy arrays instead of reading a bunch of float32 records in binary file
       record1 = np.array([202.1, 0.0], dtype='float32')
       print('record1 1st item type is', type(record1[0]))
       record2 = np.array([202.2, 0.0], dtype='float32')

       # Group records in list and create a dataframe from list
       records_list = [record1, record2]
       print('records_list 1st item of 1st item is', type(records_list[0][0]))

       # During dataframe construction, float32 items are converted to float64 items !?!
       df = pd.DataFrame.from_records(data=records_list)
       print('dataframe\'s types :')
       print(df.dtypes)

       # Real values are now different
       print('record1 1st item\'s value before then after:',  record1[0], df.iloc[0, 0])
       print('record2 1st item\'s value before then after:',  record2[0], df.iloc[1, 0])

       # Outputs
       # >>> record1 1st item type is <class 'numpy.float32'>
       # >>> records_list 1st item of 1st item is <class 'numpy.float32'>
       # >>> dataframe's types :
       # >>> 0    float64
       # >>> 1    float64
       # >>> dtype: object
       # >>> record1 1st item's value before then after: 202.1 202.10000610351562
       # >>> record2 1st item's value before then after: 202.2 202.1999969482422

1 Ответ

1 голос
/ 25 февраля 2020

Вы можете привести DataFrame к указанному c dtype с помощью astype:

df = pd.DataFrame.from_records(data=records_list).astype(np.float32)

Но сначала будет построен DataFrame из float64, а затем еще один из float32

Вы также можете напрямую указать dtype во время создания, если вы используете конструктор:

df = pd.DataFrame(data = records_list, dtype=np.float32)

Это будет непосредственно создавать фрейм данных типа float32.

...