簡體   English   中英

防止pandas在read_csv中自動推斷類型

[英]Prevent pandas from automatically inferring type in read_csv

我有一個#-separated文件有三列:第一列是整數,第二列看起來像浮點數,但不是,第三列是字符串。 我嘗試使用pandas.read_csv將其直接加載到python中

In [149]: d = pandas.read_csv('resources/names/fos_names.csv',  sep='#', header=None, names=['int_field', 'floatlike_field', 'str_field'])

In [150]: d
Out[150]: 
<class 'pandas.core.frame.DataFrame'>
Int64Index: 1673 entries, 0 to 1672
Data columns:
int_field          1673  non-null values
floatlike_field    1673  non-null values
str_field          1673  non-null values
dtypes: float64(1), int64(1), object(1)

pandas試圖變得聰明並自動將字段轉換為有用的類型。 問題是我實際上並不希望它這樣做(如果我這樣做,我會使用converters參數)。 如何防止pandas自動轉換類型?

我計划在pandas 0.10即將進行的文件解析器引擎大修中添加顯式列dtypes。 無法100%承諾,但新基礎設施的整合應該非常簡單(http://wesmckinney.com/blog/?p=543)。

我認為你最好的選擇是首先使用numpy將數據作為記錄數組讀取。

# what you described:
In [15]: import numpy as np
In [16]: import pandas
In [17]: x = pandas.read_csv('weird.csv')

In [19]: x.dtypes
Out[19]: 
int_field            int64
floatlike_field    float64  # what you don't want?
str_field           object

In [20]: datatypes = [('int_field','i4'),('floatlike','S10'),('strfield','S10')]

In [21]: y_np = np.loadtxt('weird.csv', dtype=datatypes, delimiter=',', skiprows=1)

In [22]: y_np
Out[22]: 
array([(1, '2.31', 'one'), (2, '3.12', 'two'), (3, '1.32', 'three ')], 
      dtype=[('int_field', '<i4'), ('floatlike', '|S10'), ('strfield', '|S10')])

In [23]: y_pandas = pandas.DataFrame.from_records(y_np)

In [25]: y_pandas.dtypes
Out[25]: 
int_field     int64
floatlike    object  # better?
strfield     object

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM