【问题标题】:How to map dictionary values to values of dataframe column by matching dictionary key to column name python如何通过将字典键匹配到列名python将字典值映射到数据框列的值
【发布时间】:2021-05-26 16:47:59
【问题描述】:

我想将字典中的权重映射到数据框中的某些列并计算索引(实际上是加权平均值)。

import pandas as pd
people = pd.DataFrame(
{
    'name': ['Robert', 'Sam', 'Tom'],
    'height': [160, 170, 180],
    'IQ': [100, 140, 120],
    'income': [12, 7, 4]
}
)
weights = {
    'height': 0.1,
    'IQ': 0.6,
    'income': 0.3
}

sudocode 中所需的索引为:

people['index'] = 
mean(
people['height'] * weight of height which is 0.1 + 
people['IQ'] * weight of IQ which is 0.6 + 
people['income'] * weight of income which is 0.3
)

我尝试使用map,但我必须将数据帧重新格式化为长格式并将字典映射到单列的值,为了完成这项任务,我不能。而且我不知道如何将其映射到列名

【问题讨论】:

  • 你能手动计算并告诉我第一次观察的索引列中的期望值是多少吗?

标签: python dataframe dictionary


【解决方案1】:

你可以使用 lambda 函数:

people['index'] = people.apply(lambda row : (row['height']*weights['height'] + 
                                             row['IQ']*weights['IQ'] + 
                                             row['income']*weights['income'])/3, 
                                             axis = 1) 

结果:

name height IQ income index
0 Robert 160 100 12 26.533333
1 Sam 170 140 7 34.366667
2 Tom 180 120 4 30.400000

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-08-25
    • 2018-05-03
    • 2015-07-24
    • 2018-09-21
    • 2018-08-13
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多