gpt4 book ai didi

file - 是否可以使用 Pandas 的 read_csv 读取分类列?

转载 作者:行者123 更新时间:2023-12-03 08:40:31 25 4
gpt4 key购买 nike

我试过通过 dtype参数与 read_csvdtype={n: pandas.Categorical}但这不能正常工作(结果是一个对象)。 The manual is unclear .

最佳答案

在版本 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

关于file - 是否可以使用 Pandas 的 read_csv 读取分类列?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30272300/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com