python - 基于字典向数据框添加新列

标签 python pandas dataframe dictionary

我有一个数据框和一本字典。我需要向数据帧添加一个新列并根据字典计算其值。

机器学习,根据某些表添加新功能:

score = {(1, 45, 1, 1) : 4, (0, 1, 2, 1) : 5}
df = pd.DataFrame(data = {
    'gender' :      [1,  1,  0, 1,  1,  0,  0,  0,  1,  0],
    'age' :         [13, 45, 1, 45, 15, 16, 16, 16, 15, 15],
    'cholesterol' : [1,  2,  2, 1, 1, 1, 1, 1, 1, 1],
    'smoke' :       [0,  0,  1, 1, 7, 8, 3, 4, 4, 2]},
     dtype = np.int64)

print(df, '\n')
df['score'] = 0
df.score = score[(df.gender, df.age, df.cholesterol, df.smoke)]
print(df)

我期望以下输出:

   gender  age  cholesterol  smoke    score
0       1   13            1      0      0 
1       1   45            2      0      0
2       0    1            2      1      5
3       1   45            1      1      4
4       1   15            1      7      0
5       0   16            1      8      0
6       0   16            1      3      0
7       0   16            1      4      0
8       1   15            1      4      0
9       0   15            1      2      0

最佳答案

由于 score 是一个字典(因此键是唯一的),我们可以使用 MultiIndex 对齐

df = df.set_index(['gender', 'age', 'cholesterol', 'smoke'])
df['score'] = pd.Series(score)  # Assign values based on the tuple
df = df.fillna(0, downcast='infer').reset_index()  # Back to columns
<小时/>
   gender  age  cholesterol  smoke  score
0       1   13            1      0      0
1       1   45            2      0      0
2       0    1            2      1      5
3       1   45            1      1      4
4       1   15            1      7      0
5       0   16            1      8      0
6       0   16            1      3      0
7       0   16            1      4      0
8       1   15            1      4      0
9       0   15            1      2      0

关于python - 基于字典向数据框添加新列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58611740/

相关文章:

java - 跨平台转换为 json 字符串时相同的 JSON 字符串

python - 检查列表中是否存在值为 x 的 namedtuple

apache-spark - 获取 Spark Dataframe 中特定单元格的值

r - 使用 dplyr 对多列求和时忽略 NA

python - Pandas - 列标题到行值

r - 如何输出数据框中行范围内的最大值?

python 多处理示例 itertools 多个列表

python - 具有单独训练集和验证集的 GridSearchCV 错误地还考虑了最终选择最佳模型的训练结果

python - 如何将 Pandas 系列转换为索引和值的元组

python - 这两个 Python pandas dataframe 命令有什么区别?