在pandas的read_csv函数中是否有任何选项可以自动将objectdtype的每个项目转换为str.
例如,在尝试读取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和Pandas 0.15.2
这Dtypewarning是一个Warning可以抓住并采取行动的人.有关更多信息,请参见此处 要捕获警告,我们需要将执行包装在一个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)
Run Code Online (Sandbox Code Playgroud)
结果应DataFrame与设置为str类型的有问题列相同.值得注意的是,Pandas DataFrame中的字符串列被报告为object.
| 归档时间: |
|
| 查看次数: |
5763 次 |
| 最近记录: |