我创建了一个数据框“x”
我想创建另一个数据帧y,它包含来自数据帧x的特性“小麦类型”的值
所以我执行了代码
y=X.loc[:, 'wheat_type']
当我运行以下命令时
y['wheat_type'] = y.wheat_type("category").cat.codes
我有以下错误
“Series”对象没有“wheat\u type”属性
在执行类型(X)时,我得到
<class 'pandas.core.frame.DataFrame'>
在执行类型(y)时,我得到
<class 'pandas.core.series.Series'>
是否有可能将y转换为数据帧。如果没有,请告诉我如何从x创建所需的数据帧y
最佳答案
X = pd.DataFrame({'wheat_type':[5,7,3]})
print (X)
wheat_type
0 5
1 7
2 3
#create DataFrame by subset
y=X[['wheat_type']]
#cast to category and get codes
y['wheat_type'] = y.wheat_type.astype("category").cat.codes
print (y)
wheat_type
0 1
1 2
2 0
如果有多个列,最好使用
to_frame
作为Ami
:X = pd.DataFrame({'wheat_type':[5,7,3], 'z':[4,7,9]})
print (X)
wheat_type z
0 5 4
1 7 7
2 3 9
y = X['wheat_type'].to_frame()
#cast to category and get codes
y['wheat_type'] = y.wheat_type.astype("category").cat.codes
print (y)
wheat_type
0 1
1 2
2 0
创建新数据帧的另一个解决方案是按子集和
copy
:y = X[['wheat_type']].copy()