提问者:小点点

如何应用方法/函数到Python中的数据框


功能是:

def combine(row):
    count = 0
    stage = ""
    if (str(row.doggo) == "doggo"):
        stage = "doggo"
        count += 1

    if row.floofer == "floofer":
        stage = "floofer"
        count += 1

    if row.pupper == "pupper":
        stage = "pupper"
        count += 1

    if row.pupper == "puppo":
        stage = "puppo"
        count += 1

    if count == 0:
        return pd.np.NAN
    elif count == 1:
        return stage
    else:
        return "multiple"

调用该方法时:

df_twitter_archive_clean["status"] = df_twitter_archive_clean[["doggo","floofer","pupper","puppo"]].apply(combine)

出现错误消息:

--------------------------------------------------------------------------- 属性错误回溯(最近的调用最后)在----

~/anaconda3/lib/python3。7/现场包/熊猫/核心/框架。应用中的py(自身、函数、轴、广播、原始、减少、结果类型、参数,**kwds)6485参数=参数,6486 kwds=kwds)-

~/anaconda3/lib/python3.7/site包/熊猫/核心/apply.pyget_result(自)149返回self.apply_raw()150-

~/anaconda3/lib/python3。7/现场包/熊猫/核心/应用。py在apply_标准(self)255 256中#使用序列生成器计算结果--

~/anaconda3/lib/python3。7/现场包/熊猫/核心/应用。py在apply_series_generator(self)284中尝试:285用于枚举(series_gen)中的i、v:--

在组合(行)2计数=0 3阶段 = "" ----

~/anaconda3/lib/python3。7/现场包/熊猫/核心/通用。如果为self,则为getattr(self,name)5065中的py_信息轴_可以保存标识符和名称:5066
返回self[name]-

AttributeError:(“'Series'对象没有属性'doggo','发生在索引doggo')


共1个答案

匿名用户

尝试:

df_twitter_archive_clean["status"] = df_twitter_archive_clean[["doggo","floofer","pupper","puppo"]].apply(combine, axis=1)

否则,您将按列应用该函数,如果我理解正确,您希望按行应用该函数