python - 通过聚合数据集的特定列来生成新的数据列
问题描述
我的数据集有一些我想要聚合的有趣列,因此创建了一个我可以用来做更多分析的指标。
我写的算法大约需要 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)))
解决方案
请注意,在 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
推荐阅读
- reactjs - 重定向更改 url 但不渲染组件
- mqtt - 创建 10K 连接并发送数据
- perl - 在 Perl 中将 URL 从网页打印到 STDOUT
- excel - 不匹配多个条件的值的索引/匹配公式
- xml - 如何更改 xml 文件(在 geoserver 中)中 svg 图像的颜色?是否可以在 geoserver 中更改?
- javascript - 如何在 Rust 中实现 React 组件?
- python - 将 python asyncio 与 pyee Event Emitter 结合使用
- flutter - 视频人脸识别,flutter
- python - QtWidgets.QStackedWidget() 的意外行为
- laravel - 尝试使用haversine公式在laravel中获取非对象的属性