as.type('category') 未从 'float64' 产生所需的数据类型更改
as.type('category') not yielding the desired datatype change from 'float64'
我正在尝试将数据框的特定列 df
转换为分类数据类型!或者 R Programming 所指的 factor
.
import pandas as pd
import numpy as np
df = pd.DataFrame(data=np.array([[1,1,2,2,3,3]]))
df = df.T
df[0].describe()
产量
count 6.000000
mean 2.000000
std 0.894427
min 1.000000
25% 1.250000
50% 2.000000
75% 2.750000
max 3.000000
Name: 0, dtype: float64
我转换成'category'
后
df[0] = df[0].astype('category')
df[0].describe()
产量
count 6
unique 3
top 3
freq 2
Name: 0, dtype: int64
预期输出: 在我使用正确的代码(我正在尝试弄清楚)将列的数据类型转换为类别后,我想要 df[0].describe()
显示类似
的内容
dtype: category
Categories (3, object): [1, 2, 3]
我想我有点知道我哪里出错了。我觉得我需要在转换为分类数据类型时明确提及不同的类别或不同的级别。如果你能指出我这样做的正确方向,我会很高兴的。
是否可以将具有 object
数据类型的每一列都视为 category
数据类型?如果您能突出显示 'object' 数据类型和 'category'.
之间的一些主要差异,将会很有帮助
此外,在为机器学习实现 one-hot-encoding 时,我了解到它用于将分类特征转换为数字特征,以便您可以将它们插入 sci-kit learn。那么(用更正式的术语来说)这是否意味着,one-hot-encoding 将有助于将 object
或 category
的数据类型转换为 int64
数据类型?
评论中已解决的问题:键入 df[0] 和 df[0].describe() 之间存在差异,只需打印 df[0]
即可显示数据类型作为 category
,而 df[0].describe()
将其显示为 int64。
输入然后向下滚动
df[0]
Out[942]:
0 1
1 1
2 2
3 2
4 3
5 3
Name: 0, dtype: category
Categories (3, int64): [1, 2, 3]
根据我的理解不同:category
会进行原来的水平,当你做一些数据时这是个好技巧slice
,但你不想保留value
但你想要 level
在输出中。
更改为 category
之前:
df[0].value_counts()
Out[947]:
3 2
2 2
1 2
Name: 0, dtype: int64
df1=df.iloc[2:3]
df1[0].value_counts()
Out[956]:
2 1
Name: 0, dtype: int64
更改类别后:
df[0] = df[0].astype('category')
df1=df.iloc[2:3]
df1
Out[953]:
0
2 2
df1[0].value_counts()
Out[954]:
2 1
3 0
1 0
我正在尝试将数据框的特定列 df
转换为分类数据类型!或者 R Programming 所指的 factor
.
import pandas as pd
import numpy as np
df = pd.DataFrame(data=np.array([[1,1,2,2,3,3]]))
df = df.T
df[0].describe()
产量
count 6.000000
mean 2.000000
std 0.894427
min 1.000000
25% 1.250000
50% 2.000000
75% 2.750000
max 3.000000
Name: 0, dtype: float64
我转换成'category'
后df[0] = df[0].astype('category')
df[0].describe()
产量
count 6
unique 3
top 3
freq 2
Name: 0, dtype: int64
预期输出: 在我使用正确的代码(我正在尝试弄清楚)将列的数据类型转换为类别后,我想要 df[0].describe()
显示类似
dtype: category
Categories (3, object): [1, 2, 3]
我想我有点知道我哪里出错了。我觉得我需要在转换为分类数据类型时明确提及不同的类别或不同的级别。如果你能指出我这样做的正确方向,我会很高兴的。
是否可以将具有 object
数据类型的每一列都视为 category
数据类型?如果您能突出显示 'object' 数据类型和 'category'.
此外,在为机器学习实现 one-hot-encoding 时,我了解到它用于将分类特征转换为数字特征,以便您可以将它们插入 sci-kit learn。那么(用更正式的术语来说)这是否意味着,one-hot-encoding 将有助于将 object
或 category
的数据类型转换为 int64
数据类型?
评论中已解决的问题:键入 df[0] 和 df[0].describe() 之间存在差异,只需打印 df[0]
即可显示数据类型作为 category
,而 df[0].describe()
将其显示为 int64。
输入然后向下滚动
df[0]
Out[942]:
0 1
1 1
2 2
3 2
4 3
5 3
Name: 0, dtype: category
Categories (3, int64): [1, 2, 3]
根据我的理解不同:category
会进行原来的水平,当你做一些数据时这是个好技巧slice
,但你不想保留value
但你想要 level
在输出中。
更改为 category
之前:
df[0].value_counts()
Out[947]:
3 2
2 2
1 2
Name: 0, dtype: int64
df1=df.iloc[2:3]
df1[0].value_counts()
Out[956]:
2 1
Name: 0, dtype: int64
更改类别后:
df[0] = df[0].astype('category')
df1=df.iloc[2:3]
df1
Out[953]:
0
2 2
df1[0].value_counts()
Out[954]:
2 1
3 0
1 0