Pandas read_csv 混合类型列作为字符串
Pandas read_csv mixed types columns as string
pandas' read_csv
函数中是否有任何选项可以自动将 object
dtype 的每个项目转换为 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
,可以被捕获并采取行动。有关详细信息,请参阅 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
.
如错误消息本身所述,避免 pd.read_csv
返回混合数据类型的最简单方法是设置 low_memory=False
:
df = pd.read_csv(..., low_memory=False)
然而,当使用 pd.concat
连接多个数据帧时,这种奢侈是不可用的。
pandas' read_csv
函数中是否有任何选项可以自动将 object
dtype 的每个项目转换为 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
,可以被捕获并采取行动。有关详细信息,请参阅 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
.
如错误消息本身所述,避免 pd.read_csv
返回混合数据类型的最简单方法是设置 low_memory=False
:
df = pd.read_csv(..., low_memory=False)
然而,当使用 pd.concat
连接多个数据帧时,这种奢侈是不可用的。