2015-02-23 430 views
3

pandas'read_csv函數中是否有任何選項可以自動將object dtype的每個項目轉換爲strpandas read_csv將混合類型列轉換爲字符串

例如,我在嘗試讀取一個CSV文件時的情況如下:

mydata = pandas.read_csv(myfile, sep="|", header=None)

C:\...\pandas\io\parsers.py:1159: DtypeWarning: Columns (6,635) have mixed types. Specify dtype option on import or set low_memory=False. data = self._reader.read(nrows)

是否有辦法使得(i)從印刷抑制警告,但(ii)我可以從中提取特定列的字符串中捕獲警告消息,例如6和635在這種情況下(以便我可以修復後續dtype)?或者,或者,如果我可以指定mixed types,那麼read_csv函數應該將該列中的值轉換爲str

我使用Python 3.4.2和熊貓0.15.2

+0

可以提供重現此數據的摘錄? – joris 2015-02-23 20:19:42

+0

數據文件相當大,但其中一個特定列有大約5000行,其值爲'1','2','3'或'4',並且大約1600行的值爲'Y'(還有實際上前3000行的值都是'1','2','3'或'4') – uday 2015-02-23 20:26:59

回答

6

DtypewarningWarning可以捕獲並採取行動。有關更多信息,請參閱here。要捕捉警告,我們需要將執行包裝在warnings.catch_warnings區塊中。警告消息和受影響的可使用regex被提取的列,然後用於設定使用.astype(target_type)

import re 
import pandas 
import warnings 

myfile = 'your_input_file_here.txt' 
target_type = str # The desired output type 

with warnings.catch_warnings(record=True) as ws: 
    warnings.simplefilter("always") 

    mydata = pandas.read_csv(myfile, sep="|", header=None) 
    print("Warnings raised:", ws) 
    # We have an error on specific columns, try and load them as string 
    for w in ws: 
     s = str(w.message) 
     print("Warning message:", s) 
     match = re.search(r"Columns \(([0-9,]+)\) have mixed types\.", s) 
     if match: 
      columns = match.group(1).split(',') # Get columns as a list 
      columns = [int(c) for c in columns] 
      print("Applying %s dtype to columns:" % target_type, columns) 
      mydata.iloc[:,columns] = mydata.iloc[:,columns].astype(target_type) 

結果應該是相同的DataFrame設置爲一個str類型有問題的列正確的列類型。值得注意的是,Pandas DataFrame中的字符串列被報告爲object

+0

,我想避免兩次讀取'read_csv'。我想按照原樣使用第一個'read_csv',但隨後以某種方式訪問​​Python控制檯上打印的DtypeWarning消息,以找到列號,在那裏出現警告 – uday 2015-02-23 22:24:15

+0

@請更新後的代碼執行此操作。但是,請注意,熊貓字符串列被報告爲「對象」。我的測試輸入文件產生相同的錯誤,列中的所有數據都顯示警告已被映射爲'object',因此代碼沒有外部影響。沒有看到你的輸入數據,就不可能知道你的數據是否也是如此。 – mfitzp 2015-02-24 11:43:32