默认情况下,pandas.read_csv()
将使用 dtype 对象读取字符串列。从 pandas 1.0 开始,可以改为将其读取为字符串 dtype。我正在阅读 CSV,其中大多数列都是字符串。我可以告诉熊猫(尝试)默认情况下将所有非数字列作为字符串而不是作为对象 dtypes 读取吗?
编码:
import pandas
import io
s = """2,e,4,w
3,f,5,x
4,g,6,z"""
df = pandas.read_csv(io.StringIO(s))
print(df.dtypes)
df = pandas.read_csv(
io.StringIO(s),
dtype=dict.fromkeys([1, 3], pandas.StringDtype()))
print(df.dtypes)
这导致:
2 int64
e object
4 int64
w object
dtype: object
2 int64
e string
4 int64
w string
dtype: object
我正在使用熊猫 1.0.0rc0。在编写 HDFStore 时,直接将所有内容读取为字符串 dtype 应该可以防止混合类型出现问题。