将Series转换为DataFrame

3

我创建了一个名为"x"的数据框。

我想要创建另一个数据框"y",其中包含数据框"x"中特征"wheat_type"的值。

所以我执行了以下代码:

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

当我执行以下命令时:
y['wheat_type'] = y.wheat_type("category").cat.codes

我遇到了以下错误

'Series' 对象没有属性 'wheat_type'

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

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

执行type(y)后,我得到了:
 <class 'pandas.core.series.Series'>

有没有可能将y转换为数据框?如果不行,请告诉我如何从x创建所需的数据框y。

2个回答

2
看起来需要使用 astype 和 to_frame 两个方法,具体内容请参考 astypeto_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,如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

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

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

谢谢,它解决了我的问题。在其他代码中,我运行了一个简单的“df = pd.read_csv()”代码,但当我执行df.dtypes()时,我得到了相同的错误“'Series' object is not callable”。如何修复? - SHIVAM GOYAL
你只需要省略 () - print df.dtypes - jezrael
请参见dtypes - jezrael

1

有一个特殊的方法可以实现 - 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

我使用了上述命令,当我执行'type(y)'时,现在输出为'<class 'pandas.core.frame.DataFrame'>'。但是当我执行代码'y['wheat_type'] = y.wheat_type("category").cat.codes'时,仍然出现错误''Series' object is not callable'。有任何想法为什么会这样? - SHIVAM GOYAL
@SHIVAMGOYAL - 看看我的答案,你需要将其转换为 category - jezrael
好的,Jezrael已经回答了你的问题:-)。无论如何,我验证了df.a.to_frame().a.astype('category')是有效的。 - Ami Tavory

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接