如何使用字典作为量规使用pd.apply()为数据帧赋值

问题描述 投票:1回答:1
def create_rubric(number, df, col):
"""
First finds all the unique fields then segments them in quintiles.
Uses the quintiles to give ratings to the original data
"""

    sorted_col = df[col].sort_values()
    unique_val = sorted_col.unique()
    unique_cut = pd.qcut(unique_val,number,labels=False)
    unique_dict = {"Items" : unique_val, "Labels" : unique_cut}
    df = pd.DataFrame(unique_dict)
    rubric = {}
    rubric[1] = df[df.Labels == 0]
    rubric[2] = df[df.Labels == 1]
    rubric[3] = df[df.Labels == 2]
    rubric[4] = df[df.Labels == 3]
    rubric[5] = df[df.Labels == 4]
    return rubric

def frequency_star_rating(x, rubric):
"""
Uses rubric to score the rows in the dataframe
"""
    for rate, key in rubric.items():
        if x in key:
            return rate

rubric = create_rubric(5,rfm_report,"ordersCount")
rfm_report["Frequency Rating"] = rfm_report["ordersCount"].apply(frequency_star_rating, rubric)

我写了两个应该互相交互的函数。一个人创建一个最终在字典中的评分量规,另一个应该使用该字典对大约700,000行的数据帧中的行进行评分。由于某种原因,我不断得到“系列对象是可变的,不能被散列”的错误。我真的无法弄清楚这样做的最好方法。我写的功能错了吗?

python pandas apply
1个回答
0
投票

如果您能提供玩具数据集,那么我们可以快速运行您的代码并查看错误发生的位置。

您得到的错误是试图告诉您pd.Series对象不能用作字典的键。原因是Python字典是哈希表。因此,他们只接受可混合数据类型作为关键。例如,字符串和整数是可清除的,但列表不是。所以以下工作正常:

fine_dict = {'John': 1, 'Lilly': 2}

虽然这个将扔一个TypeError

wrong_dict = {['John']: 1, ['Lilly']: 2}

错误将如下所示:TypeError:unhashable type:'list'。

所以我的预感是你的代码中的某个地方,你试图使用一个Series对象作为字典的关键字,你不应该这样做,因为它不可用。

© www.soinside.com 2019 - 2024. All rights reserved.