将序列转换为数据帧

2024-04-26 17:30:42 发布

您现在位置:Python中文网/ 问答频道 /正文

我创建了一个数据框“x”

我想创建另一个数据帧y,它包含来自数据帧x的特性“小麦类型”的值

所以我执行了代码

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

当我运行以下命令时

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

我有以下错误

'Series' object has no attribute 'wheat_type'

在执行类型(X)时,我得到

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

在执行类型(y)时,我得到

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

是否有可能将y转换为数据帧。如果没有,请告诉我如何从x创建所需的数据帧y


Tags: 数据代码core命令类型pandastype特性
2条回答

看起来需要^{}^{}

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

创建新数据帧的另一个解决方案是按子集和^{}

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

有一个特殊的方法-^{}

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

相关问题 更多 >