0.19.0
版本中,您可以在dtype='category'
中使用参数read_csv
:
data = 'col1,col2,col3\na,b,1\na,b,2\nc,d,3'
df = pd.read_csv(pd.compat.StringIO(data), dtype='category')
print (df)
col1 col2 col3
0 a b 1
1 a b 2
2 c d 3
print (df.dtypes)
col1 category
col2 category
col3 category
dtype: object
如果要指定类别列,请使用
dtype
与字典:
df = pd.read_csv(pd.compat.StringIO(data), dtype={'col1':'category'})
print (df)
col1 col2 col3
0 a b 1
1 a b 2
2 c d 3
print (df.dtypes)
col1 category
col2 object
col3 int64
dtype: object
这个问题发布已经有 8 年多了,但是
dtype={n: pandas.Categorical}
不起作用,因为 pd.Categorical
是一个顶级函数,它将列转换为类别 dtype,而不是 dtype 实例本身。您可以使用 pd.CategoricalDtype()
来实现。
df = pd.read_csv("my_data.csv", dtype=pd.CategoricalDtype())
对于特定列,例如
col1
:
df = pd.read_csv("my_data.csv", dtype={'col1': pd.CategoricalDtype()})
显式使用 dtype 实例(相对于传递快捷方式
'category'
)的优点是因为您可以做两件事:
TypeError: Cannot setitem on a Categorical with a new category (b), set the categories first
。为了完全防止此错误,您可以在开头传递类别列表。使用@jezrael的答案中的示例,以下代码演示了一个示例:
import io
data = 'col1,col2,col3\na,b,1\na,b,2\nc,d,3'
df = pd.read_csv(io.StringIO(data), dtype={'col1': pd.CategoricalDtype(categories=['c', 'b', 'a'], ordered=True)})
然后当我们仔细检查
df['col1']
时:
df['col1']
0 a
1 a
2 c
Name: col1, dtype: category # <--- was read in as categorical dtype
Categories (3, object): ['c' < 'b' < 'a'] # <--- 'b' is a category even though it doesn't exist in the column yet