pandas 是否可以使用熊猫的 read_csv 读取分类列?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/30272300/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Is it possible to read categorical columns with pandas' read_csv?
提问by Emre
I have tried passing the dtypeparameter with read_csvas dtype={n: pandas.Categorical}but this does not work properly (the result is an Object). The manual is unclear.
我试过dtype用read_csvas传递参数,dtype={n: pandas.Categorical}但这不能正常工作(结果是一个对象)。说明书不清楚。
回答by jezrael
In version 0.19.0you can use parameter dtype='category'in read_csv:
在版本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
If want specify column for category use dtypewith dictionary:
如果要指定用于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
回答by Alexander
Categorical is not a valid dtype.
Categorical 不是有效的dtype。
This StackOverflow postcontains details for how to store categorical data in a text file.
此StackOverflow 帖子包含有关如何在文本文件中存储分类数据的详细信息。

