python - 如何根据另一个表的检查替换熊猫数据框中列中的值
问题描述
我有一个数据框df
import pandas as pd
df = pd.DataFrame({"Cust": ['cst1', 'cst1', 'cst1', 'cst2', 'cst2', 'cst2', 'cst3', 'cst3', 'cst3', 'cst4', 'cst4', 'cst4'],
"act": ['ac1', 'ac2', 'ac3','ac1', 'ac2', 'ac3','ac1', 'ac2', 'ac3','ac1', 'ac2', 'ac3' ],
"rating": ['a', 'b', 'c', 'b', 'b', 'c', 'h', 'i', 'i', 'c', 'c', 'a']})
df_priority = pd.DataFrame({"rating":['a','b', 'c', 'd', 'e', 'f','g','h','i','j','k','l','m','n','o','p','q','r','s'],
"priority":[1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19]})
和另一个具有评级优先级的数据框
我的df表看起来像:
Cust act rating
0 cst1 ac1 a
1 cst1 ac2 b
2 cst1 ac3 c
3 cst2 ac1 b
4 cst2 ac2 b
5 cst2 ac3 c
6 cst3 ac1 h
7 cst3 ac2 i
8 cst3 ac3 i
9 cst4 ac1 c
10 cst4 ac2 c
11 cst4 ac3 a
我的 df_priority 表看起来像:
rating priority
0 a 1
1 b 2
2 c 3
3 d 4
4 e 5
5 f 6
6 g 7
7 h 8
8 i 9
9 j 10
10 k 11
11 l 12
12 m 13
13 n 14
14 o 15
15 p 16
16 q 17
17 r 18
18 s 19
我需要检查df表中每个cust的评级值并将其替换为该 cust的最大优先级评级。
例如,对于 cust = cst1,我应该将所有三个记录的评分为a ,因为 a的优先级高于 b 和 c。同样,它应该适用于每个客户,然后应该检查优先级表并相应地更新。
我的预期输出是:
Cust act rating
0 cst1 ac1 a
1 cst1 ac2 a
2 cst1 ac3 a
3 cst2 ac1 b
4 cst2 ac2 b
5 cst2 ac3 b
6 cst3 ac1 h
7 cst3 ac2 h
8 cst3 ac3 h
9 cst4 ac1 a
10 cst4 ac2 a
11 cst4 ac3 a
我如何在 Pandas 中做到这一点?
解决方案
我们可以map
使用transform
idxmim
然后将其分配回reindex
df['new']=df.rating.map(dict(zip(df_priority.rating,df_priority.priority)))
df.groupby('Cust').new.transform('idxmin')
0 0
1 0
2 0
3 3
4 3
5 3
6 6
7 6
8 6
9 11
10 11
11 11
Name: new, dtype: int64
df['newcol'] = df.rating.reindex(df.groupby('Cust').new.transform('idxmin')).tolist()
df
Cust act rating new newcol
0 cst1 ac1 a 1 a
1 cst1 ac2 b 2 a
2 cst1 ac3 c 3 a
3 cst2 ac1 b 2 b
4 cst2 ac2 b 2 b
5 cst2 ac3 c 3 b
6 cst3 ac1 h 8 h
7 cst3 ac2 i 9 h
8 cst3 ac3 i 9 h
9 cst4 ac1 c 3 a
10 cst4 ac2 c 3 a
11 cst4 ac3 a 1 a
推荐阅读
- angular - 单击按钮 Angular 时的去抖动时间
- django - TabError:视图缩进中制表符和空格的不一致使用 - Django
- r - 有没有办法在 R 中找到字符串中单词的平均长度?
- javascript - 连接到mongodb的问题
- ffmpeg - tsduck 合并两个 SPTS
- swift - 圆角tableview标题swift
- javascript - Vuex 数据获取:如何在不同的组件中等待数据
- javascript - 在对象数组内连接对象数组
- c++ - 使用 lock_guard 同时从多个线程访问同一对象时出现问题
- api-gateway - 如何从 azure 应用程序网关重写 url 中删除 url 的截断部分