2015-05-27 4 views
9

DaWie erzwinge ich pandas read_csv, um float32 für alle Float-Spalten zu verwenden?

  • Ich brauche keine doppelte Genauigkeit
  • Meine Maschine Speicher begrenzt ist, und ich möchte größere Datenmengen verarbeiten
  • Ich brauche die extrahierten Daten zu übergeben (als Matrix) zu BLAS-Bibliotheken und BLAS-Aufrufe für einfache Genauigkeit sind 2x schneller als für doppelte Präzisionsäquivalenz.

Beachten Sie, dass nicht alle Spalten in der rohen CSV-Datei Float-Typen haben. Ich muss nur Float32 als Standard für Float-Spalten festlegen.

Antwort

8

Versuchen:

import numpy as np 
import pandas as pd 

# Sample 100 rows of data to determine dtypes. 
df_test = pd.read_csv(filename, nrows=100) 

float_cols = [c for c in df_test if df_test[c].dtype == "float64"] 
float32_cols = {c: np.float32 for c in float_cols} 

df = pd.read_csv(filename, engine='c', dtype=float32_cols) 

Diese erste eine Probe von 100 Reihen von Daten liest (modifizieren, wie erforderlich), um den Typ jeder Spalte zu bestimmen.

Er erstellt eine Liste der Spalten, die 'float64' sind, und verwendet dann Wörterbuchverständnis, um ein Wörterbuch mit diesen Spalten als Schlüssel und 'np.float32' als Wert für jeden Schlüssel zu erstellen.

Schließlich liest es die gesamte Datei mit der "c" -Engine (erforderlich für die Zuordnung von dtypes zu Spalten) und übergibt dann das float32_cols-Wörterbuch als Parameter an dtype.

df = pd.read_csv(filename, nrows=100) 
>>> df 
    int_col float1 string_col float2 
0  1  1.2   a  2.2 
1  2  1.3   b  3.3 
2  3  1.4   c  4.4 

>>> df.info() 
<class 'pandas.core.frame.DataFrame'> 
Int64Index: 3 entries, 0 to 2 
Data columns (total 4 columns): 
int_col  3 non-null int64 
float1  3 non-null float64 
string_col 3 non-null object 
float2  3 non-null float64 
dtypes: float64(2), int64(1), object(1) 

df32 = pd.read_csv(filename, engine='c', dtype={c: np.float32 for c in float_cols}) 
>>> df32.info() 
<class 'pandas.core.frame.DataFrame'> 
Int64Index: 3 entries, 0 to 2 
Data columns (total 4 columns): 
int_col  3 non-null int64 
float1  3 non-null float32 
string_col 3 non-null object 
float2  3 non-null float32 
dtypes: float32(2), int64(1), object(1) 
Verwandte Themen