将 Series 转换为 DataFrame

convert Series to DataFrame

我创建了一个数据框 'x'

我想创建另一个数据框 y,它包含来自数据框 x

的特征 'wheat_type' 的值

所以我执行了代码

y=X.loc[:, 'wheat_type']

当我运行下面的命令

y['wheat_type'] = y.wheat_type("category").cat.codes

我收到以下错误

'Series' object has no attribute 'wheat_type'

在执行 type(X) 时,我得到了

 <class 'pandas.core.frame.DataFrame'>

在执行 type(y) 时,我得到了

 <class 'pandas.core.series.Series'>

是否有可能将 y 转换为 dataframe.If 不,请告诉我如何从 x

创建所需的数据帧 y

有一个特殊的方法 - pd.Series.to_frame

In [2]: df = pd.DataFrame({'a': range(4)})

In [3]: df.a
Out[3]: 
0    0
1    1
2    2
3    3
Name: a, dtype: int64

In [4]: df.a.to_frame()
Out[4]: 
   a
0  0
1  1
2  2
3  3

看来需要astype and to_frame:

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 作为指示 :

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

另一种创建新 DataFrame 的解决方案是通过子集和 copy:

y = X[['wheat_type']].copy()