在Python中创建一个列

时间:2018-01-12 14:58:26

标签: python

我正在尝试使用以下python代码创建列Age的类别:

for x in range(len(Ttrain.Age)):
       if Ttrain.Age(x) == 0:
             Ttrain.Age_Group(x) == 'Missing'
        elif 0 < Ttrain.Age(x) <= 18:
             Ttrain.Age_Group(x) == 'Young'
        elif 19 < Ttrain.Age(x) <= 40:
             Ttrain.Age_Group(x) == 'Adult'
        elif 41 < Ttrain.Age(x) <= 60:
             Ttrain.Age_Group(x) == 'Middle_Aged'
        elif Ttrain.Age(x) > 60:
             Ttrain.Age_Group(x) == 'Old'
 % (x)

这样Age_Group列将包含类别。但我收到以下错误:

  

TypeError:'Series'对象不可调用

请注意,我已将年龄列中的所有缺失值替换为0。

1 个答案:

答案 0 :(得分:1)

您的代码中存在许多问题,正如@Uvar在评论中提到的那样,表明您没有很好地掌握python的基本原理。我强烈建议您阅读pythonpandas免费在线提供的许多教程之一。

让我尝试解释一些错误,修复代码,并尝试提供更好的解决方案。

函数调用(__call__)与获取项目(__getitem__

python ()中的括号引用函数调用。当您撰写if Ttrain.Age(x) == 0:时,您要执行的操作是访问x Series的{​​{1}}个元素。但是解释器认为你想把Ttrain.Age称为函数(因此你的错误信息)。正确的语法是使用方括号Series进行索引:[]

分配与平等

双等号(if Ttrain.Age[x] == 0:)用于测试相等性。一个相等的(==)符号用于分配。

=正在测试Ttrain.Age_Group[x] == 'Missing' x中的Series个元素是否等于Ttrain.Age_Group string。你打算写的是:'Missing'

初始化之前的访问

将以上两点放在一起:

Ttrain.Age_Group[x] = 'Missing'

这是因为for x in range(len(Ttrain)): if Ttrain.Age[x] == 0: Ttrain.Age_Group[x] = 'Missing' ... AttributeError: 'DataFrame' object has no attribute 'Age_Group' 系列尚不存在,因此翻译人员不知道该怎么做。您需要先定义此列。

Age_Group

但这样做会引起以下警告:

  

SettingWithCopyWarning:尝试在a的副本上设置值   来自DataFrame的切片

这是一件坏事。我不打算详细介绍。我会把它作为练习留给research and understand为什么。

全部放在一起

以下是代码的清理版本。您会注意到我也更改了Ttrain['Age_Group'] = None for x in range(len(Ttrain)): if Ttrain.Age[x] == 0: Ttrain.Age_Group[x] = 'Missing' 条件。我会把这个留给你思考为什么。

elif

更好的方法

通常,迭代import pandas as pd # mock up some dummy data Ttrain = pd.DataFrame({'Age': range(0, 80, 10)}) # Ttrain['Age_Group'] = None # don't need this since we're using loc for x in range(len(Ttrain)): if Ttrain.Age[x] == 0: Ttrain.loc[x, 'Age_Group'] = 'Missing' elif Ttrain.Age[x] <= 18: Ttrain.loc[x, 'Age_Group'] = 'Young' elif Ttrain.Age[x] <= 40: Ttrain.loc[x, 'Age_Group'] = 'Adult' elif Ttrain.Age[x] <= 60: Ttrain.loc[x, 'Age_Group'] = 'Middle_Aged' elif Ttrain.Age[x] > 60: Ttrain.loc[x, 'Age_Group'] = 'Old' 是不好的。它很慢,在许多情况下,有更好的方法来做你想做的事情。有时,它是不可避免的,但在这个例子中并非如此。 (查看pandas面具)。

dataframe

最终输出

这是最终数据框的样子:

import pandas as pd

# create a dummy dataset for this example
Ttrain = pd.DataFrame({'Age': range(0, 80, 10)})

Ttrain.loc[Ttrain.Age == 0, 'Age_Group'] = 'Missing'
Ttrain.loc[(Ttrain.Age > 0) & (Ttrain.Age <= 18), 'Age_Group'] = 'Young'
Ttrain.loc[(Ttrain.Age > 18) & (Ttrain.Age <= 40), 'Age_Group'] = 'Adult'
Ttrain.loc[(Ttrain.Age > 40) & (Ttrain.Age <= 60), 'Age_Group'] = 'Middle_Aged'
Ttrain.loc[(Ttrain.Age > 60), 'Age_Group'] = 'Old'
祝你好运。