【问题标题】:How to add the key of a dictionary to dataframe of value is in range of a dictionary value in python如何将字典的键添加到数据帧的值在python中的字典值范围内
【发布时间】:2022-11-08 05:19:39
【问题描述】:

示例 df 如下所示:

Price   Group
10  apple
8   apple
7   apple
6   apple
10  apple
12  berry
11  berry
11  berry
7   berry
9   berry

每个键都有一系列值的嵌套字典:

apple:{'A':[9, 10], 'B':[6, 8], 'C':[3-5]}

berry:{'A':[11, 12], 'B':[6, 9]}

如果Price 在每个键的值范围内,则将Cat 列添加到df,每个Group 中都有相应的键。输出:

Price   Group    Cat
    10  apple    A
    8   apple    B
    7   apple    B
    6   apple    B
    10  apple    A
    12  berry    A
    11  berry    A
    11  berry    A
    7   berry    B
    9   berry    B

这可以使用 python 中的任何内置函数或使用包含 df 和 dicts 的函数的任何其他方式来实现吗?

【问题讨论】:

    标签: python dictionary


    【解决方案1】:

    使用df DataFrame 和

    D = {
        "apple":{'A':[9, 10], 'B':[6, 8]},
        "berry":{'A':[11, 12], 'B':[6, 9]}
    }
    

    尝试:

    df["cat"] = df[["Price", "Group"]].apply(lambda x: next(k for k,v in D[x[1]].items() if v[0] <= x[0] <= v[1] ), axis = 1)
    
    print(df)
    

    输出:

    Price   Group   cat
        10  apple   A
        8   apple   B
        7   apple   B
        6   apple   B
        10  apple   A
        12  berry   A
        11  berry   A
        11  berry   A
        7   berry   B
        9   berry   B
    

    这不会检查是否存在至少一个适当的时间间隔,并且可能会在以下情况下崩溃无间隔适合(因为 next() 将应用于空迭代器)

    【讨论】:

    • 它必须检查 df 中的值是否适合 dict 中的间隔,否则它将根据什么标准将值添加到 df 中的新列?
    • 它会这样做(检查输出)。但如果没有间隔适合该值,它可能会崩溃
    • 不幸的是,有可能出现这种情况并且它会破裂。
    • 那么预期的行为是什么?
    猜你喜欢
    • 2019-11-09
    • 2016-10-29
    • 2013-09-19
    • 2017-01-04
    • 2018-09-26
    • 2019-11-21
    • 2020-04-12
    • 1970-01-01
    • 2018-05-27
    相关资源
    最近更新 更多