gpt4 book ai didi

python - Pandas 数据框中的分类变量?

转载 作者:太空狗 更新时间:2023-10-29 16:58:33 25 4
gpt4 key购买 nike

我正在学习 Wes 的 Python For Data Analysis,我遇到了书中没有解决的奇怪问题。

在下面的代码中,基于他的书的第 199 页,我创建了一个数据框,然后使用 pd.cut() 创建了 cat_obj。按照书上的说法,cat_obj

"a special Categorical object. You can treat it like an array of strings indicating the bin name; internally it contains a levels array indicating the distinct category names along with a labeling for the ages data in the labels attribute"

太棒了!但是,如果我使用完全相同的 pd.cut() 代码(在下面的 [5] 中)创建数据框的新列(称为 df['cat']),该列不被视为特殊的分类变量,而只是被视为常规的 pandas 系列。

那么,如何在被视为分类变量的数据框中创建列?

In [4]:

import pandas as pd

raw_data = {'name': ['Miller', 'Jacobson', 'Ali', 'Milner', 'Cooze', 'Jacon', 'Ryaner', 'Sone', 'Sloan', 'Piger', 'Riani', 'Ali'],
'score': [25, 94, 57, 62, 70, 25, 94, 57, 62, 70, 62, 70]}
df = pd.DataFrame(raw_data, columns = ['name', 'score'])

bins = [0, 25, 50, 75, 100]
group_names = ['Low', 'Okay', 'Good', 'Great']

In [5]:
cat_obj = pd.cut(df['score'], bins, labels=group_names)
df['cat'] = pd.cut(df['score'], bins, labels=group_names)
In [7]:

type(cat_obj)
Out[7]:
pandas.core.categorical.Categorical
In [8]:

type(df['cat'])
Out[8]:
pandas.core.series.Series

最佳答案

这可能是由于 setter- 的这种行为而发生的:

示例 getter 和 setter-

class a:
x = 1
@property
def p(self):
return int(self.x)

@p.setter
def p(self,v):
self.x = v
t = 1.32
a().p = 1.32


print type(t) --> <type 'float'>
print type(a().p) --> <type 'int'>

目前 df 只接受 Series 数据,它的 setter 将 Categorial data 转换为 Seriesdf 类别支持将在下一个 Pandas 版本中到期。

关于python - Pandas 数据框中的分类变量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23450735/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com