【问题标题】:raise KeyError(key) in pandas while using apply function and trying get 2 input在使用 apply 函数并尝试获取 2 个输入时在 pandas 中引发 KeyError(key)
【发布时间】:2022-11-11 02:52:51
【问题描述】:

我想在 .apply 函数中获取 2 个实体并检查它,但我收到了 pandas.errors.IndexingError: Too many indexers 错误。

import pandas as pd

dict2 = {
    "name": ["kambiz", "ali", "mmd", "sara"],
    "age": [19, 19, 14, 12],
}

df = pd.DataFrame(dict2)


def show_if(age, name):
    if age == 19:
        if name == "kambiz":
           return "you are kambiz and 19"
        elif name == "ali":
           return "you are ali and 19"
    else:
        return "not available"


df["19 ages"] = df.apply(lambda x: show_if(x.loc[:, x["age"]], x.loc[:, x["name"]]), axis=1)
print(df)

如何得到两个实体,然后检查它?谢谢你的帮助 。

【问题讨论】:

    标签: python pandas numpy


    【解决方案1】:

    不要使用apply,而是使用矢量方法:

    import numpy as np
    
    df["19 ages"] = np.where(df['age'].eq(19),
                             '19 in this group is '+df['name'],
                             'not available')
    

    输出:

         name  age                     19 ages
    0  kambiz   19  19 in this group is kambiz
    1     ali   17               not available
    2     mmd   14               not available
    3    sara   12               not available
    

    【讨论】:

    • 请查看我的问题
    猜你喜欢
    • 2017-04-12
    • 1970-01-01
    • 2022-01-07
    • 2019-04-29
    • 1970-01-01
    • 2021-06-10
    • 2022-06-11
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多