python - 使用不同的 {key:value} 字典运行 Groupby
问题描述
在以下代码中:
import pandas as pd
import numpy as np
import random
sz = 50
df = pd.DataFrame({'Group': pd.Series(random.choice(['A', 'B']) for _ in range(sz)),
'Key': pd.Series(np.random.randint(2, high=5, size=sz))})
dictforA = {2: 0.1, 3: 0.8, 4: 0.2}
dictforB = {3: 0.9}
...想要分配一个名为的新列Value
,该列基于其各自的字典。缺失值将是 NaN。
编码:
df.assign(Value=df.groupby('Group').apply(lambda x: np.where(x.index == 'A', dictforA[x.Key], dictforB[x.Key])))
给
TypeError: 'Series' objects are mutable, thus they cannot be hashed
我哪里错了?
解决方案
您可以从 Group 创建一个映射器到您的字典并使用pd.Series.map
mapper = {'A': dictforA,
'B': dictforB}
df['Value'] = df.groupby('Group').Key.apply(lambda s: s.map(mapper[s.name]))
>>> print(df.head(10))
Group Key Value
0 B 3 0.9
1 A 2 0.1
2 B 3 0.9
3 A 3 0.8
4 A 3 0.8
5 A 2 0.1
6 B 2 NaN
7 B 2 NaN
8 A 4 0.2
9 A 2 0.1
推荐阅读
- xamarin.forms - 黑莓与Android OS6.0.1
- c# - 将 html 文件转换为独立的桌面应用程序
- swift - 如何使 JSON 数据持久化以供离线使用(Swift 4)
- angularjs - 在 Django 中,如何使用 angularjs 设置某个请求会话?
- swift - 当我创建一个 segue 以注销时,一个导航控制器突然出现 - Swift
- x86 - 有没有办法确定发生了 SMM 中断?
- spring - 异常连接被拒绝
- c++11 - 具有自定义键类型的 std::unordered_set 允许插入重复键
- java - Android如何限制单个应用实例?
- proof - 在 Idris 中为决策函数构建证明