【问题标题】:Couldn't make a new column from the data provided within the data frame无法根据数据框中提供的数据创建新列
【发布时间】:2018-05-15 21:19:30
【问题描述】:

我正在尝试使用 apply 函数在 Titanic 数据框中添加列。但是,我在定义函数的地方遇到错误。我也尝试应用 .all(), .any() 但我无法得到正确答案。有什么办法解决?

titanic = sns.load_dataset('titanic')
titanic.head()

titanic['With(out)'] = titanic.sibsp + titanic.parch

def alone(n):
    if titanic['With(out)'] > 0:
        return 'With Family'
    else: 
        return 'Alone'

titanic['Alone'] = titanic['With(out)'].apply(alone)

ValueError:Series 的真值不明确。使用 a.empty、a.bool()、a.item()、a.any() 或 a.all()。

【问题讨论】:

    标签: python if-statement apply seaborn


    【解决方案1】:

    你的函数从不使用它的参数n;那应该敲响警钟。使用

    def alone(n):
        if n > 0:
            return 'With Family'
        else: 
            return 'Alone'
    

    【讨论】:

    • 非常感谢。它永远不会在我脑海中浮现。
    猜你喜欢
    • 1970-01-01
    • 2021-11-10
    • 2017-01-03
    • 2021-11-04
    • 2018-07-01
    • 1970-01-01
    • 1970-01-01
    • 2021-11-11
    • 2020-10-25
    相关资源
    最近更新 更多