首页 > 解决方案 > 通过聚合数据集的特定列来生成新的数据列

问题描述

我的数据集有一些我想要聚合的有趣列,因此创建了一个我可以用来做更多分析的指标。

我写的算法大约需要 3 秒才能完成,所以我想知道是否有更有效的方法来做到这一点。

def financial_score_calculation(df, dictionary_of_parameters):
    for parameter in dictionary_of_parameters:
        for i in dictionary_of_parameters[parameter]['target']:
            index = df.loc[df[parameter] == i].index
            for i in index:
                old_score = df.at[i, 'financialliteracyscore']
                new_score = old_score + dictionary_of_parameters[parameter]['score']
                df.at[i, 'financialliteracyscore'] = new_score
    for i in df.index:
        old_score = df.at[i, 'financialliteracyscore']
        new_score = (old_score/27.0)*100 #converting score to percent value
        df.at[i, 'financialliteracyscore'] = new_score

    return df

这是 dictionary_of_parameters 的截断版本:

dictionary_of_parameters = {
    # money management parameters
    "SatisfactionLevelCurrentFinances": {'target': [8, 9, 10], 'score': 1},
    "WillingnessFinancialRisk": {'target': [8, 9, 10], 'score': 1},
    "ConfidenceLevelToEarn2000WithinMonth": {'target': [1], 'score': 1},
    "DegreeOfWorryAboutRetirement": {'target': [1], 'score': 1},
    "GoodWithYourMoney?": {'target': [7], 'score': 1}
    }

编辑:为 df 生成玩具数据

df = pd.DataFrame(columns = dictionary_of_parameters.keys())
df['financialliteracyscore'] = 0
for i in range(10):
    df.loc[i] = dict(zip(df.columns,2*i*np.ones(6)))

标签: pythonpandasdataframe

解决方案


请注意,在 Pandas 中,您可以使用at. 在下面的四行代码中,index是一个列表,可用于索引loc

for parameter in dictionary_of_parameters:
    index = df[df[parameter].isin(dictionary_of_parameters[parameter]['target'])].index
    df.loc[index,'financialliteracyscore'] += dictionary_of_parameters[parameter]['score']
df['financialliteracyscore'] = df['financialliteracyscore'] /27.0*100

这是一个参考,尽管我个人在早期的编程中从未发现它有用... https://pandas.pydata.org/pandas-docs/stable/indexing.html


推荐阅读