所以我有一个非常愚蠢的问题,我已经绊倒了几个小时了。 我正在使用 graphlab create 练习 kaggle 的 Titanic ML 练习。
现在我想替换表中的一些值。例如,我想将年龄设置(作为测试)Pclass==1 的年龄为 38,Pclass==2 的年龄设置为 30,Pclass==3 的年龄设置为 26
我尝试了很多方法来做到这一点,但我迷失了。
我现在所拥有的是:
df = gl.SFrame(data)
df[(df["Pclass"]==1)] #will print the rows of the table where Pclass=1
df["Age"][df["Pclass"]==1] #will display an array containg only the column "Age" for Pclass=1
现在我正在尝试正确使用 SFrame.apply,但我很困惑。
我已经尝试过
df["Age"][df["Pclass"]==1].apply(lambda x: 38)
这会返回一个具有正确值的数组,但我无法将其应用于 SFrame。 例如,我尝试过:
df = df["Age"][df["Pclass"]==1].apply(lambda x: 38)
但是现在我的 DataFrame 变成了一个列表......(显然)
我也尝试过:
df["Age"] = df["Age"][df["Pclass"]==1].apply(lambda x: 38)
但我收到以下错误:“RuntimeError:运行时异常。列“__PassengerId-Survived-Pclass-Sex-Age-Fare”的大小与当前列的大小不同!”
我确信解决方案非常简单,但我太困惑了,无法自己找到它。
最终我想要类似的东西 df["Age"] = Something.apply(lambda x: 38 if Pclass==1 else 30 if Pclass==2 else 26 if Pclass==3)
谢谢。
最佳答案
您可以使用如下替代代码:
只需在原始Sframe中创建一个新列'Pclass_',即可:
df['Pclass_'] = [1 if item == 38 else 2 if item == 30 else 3 if item == 26 else 4 for item in df['Age']]
您可以在列表中使用任何类型的 (if-else-if) 条件。
关于python - 图实验室 : replacing values in Sframe and filtering,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42704263/