【发布时间】:2020-01-22 09:13:23
【问题描述】:
默认情况下,pandas.read_csv() 将使用 dtype 对象读取字符串列。从 pandas 1.0 开始,可以改为将其读取为字符串 dtype。我正在阅读 CSV,其中大多数列都是字符串。我可以告诉 pandas(尝试)默认将所有非数字列作为字符串而不是对象 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。直接将所有内容读取为字符串 dtype 应该可以防止 problems with mixed types when writing an HDFStore。
【问题讨论】:
-
决定启动pandas-1.0 标签,因为它的发布迫在眉睫,其重大变化可能会引发许多具体问题。见this question on meta。
标签: python pandas dataframe io pandas-1.0