基于一列或多列中的值,根据映射字典的键值对,得到新列
最后修改日期:2021年11月19日
Ps: 如果本文有给你一些启发或者帮助的话,麻烦帮忙点个收藏、关注或者赞呗 (≧▽≦)/
# example
print(data)
'''
A Num ... B priority
0 Y 962 ... P Highest
... ... ... ... ... ...
556 t 84 ... F Medium
... ... ... ... ... ...
560 t 193 ... F Low
'''
基于单列中的值,提出自定义字典。此例中,有自定义字典1个,键为A列中的值,值为被映射到C列中相应的值。
# key, 'A'; value, 'C'; mapping 'A' values to 'C' values
A_to_C_Short = {
...
('Y', ...): 'P',
...
(..., 't'): 'Others'
} # len(A_to_C_Short.keys()) = 6
'''
m = 0
for n in A_to_C_Short.keys():
m += len(n)
# m = 26
# there are 26 values in total
'''
键为A列中的值。
# 'A'
A = data.groupby('A').agg('sum').index.to_list() # len(A) = 49
'''
['A', 'B', ...]
'''
键为A列中的值,值为经过字典映射后理应被映射到C列中相应的值。
# primary mapping: mapping 'A' items in 'A' col to get a A_to_C full dict
A_to_C_Full = {}
for i in A:
for j in A_to_C_Short:
if i in j:
A_to_C_Full[i] = A_to_C_Short[j]
'''
print(A_to_C_Full):
{..., 'Y': 'P', ..., 't': 'Others', ...}
print(len(A_to_C_Full))
26
'''
经过完整字典将基于A列中的值映射到C列中相应的值。
# secondary mapping: mapping 'A' values in 'A' col to new values in 'C' col by A_to_C_Full dict
data['C'] = data['A'].map(A_to_C_Full).fillna(0)
'''
A Num ... C
0 Y 962 P
... ... ... ... ...
556 t 84 ... Others
... ... ... ... ...
560 t 193 ... Others
'''
# example
print(data)
'''
A Num ... B priority
0 Y 962 ... P Highest
... ... ... ... ... ...
556 t 84 ... F Medium
... ... ... ... ... ...
560 t 193 ... F Low
'''
基于多列中的值,提出自定义字典。此例中,有自定义字典2个,键为A或B列中的值,值为被映射到C列中相应的值。
键为A列中的值,值为被映射到C列中相应的值。
# key, 'A'; value, 'C'; mapping 'A' values to 'C' values
A_to_C_Short = {
...
('Y', ...): 'P',
...
(..., 't'): 'Others'
} # len(A_to_C_Short.keys()) = 6
'''
m = 0
for n in A_to_C_Short.keys():
m += len(n)
# m = 26
# there are totally 26 items in 6 keys
'''
键为B列中的值,值为被映射到C列中相应的值。
# key, 'B'; value, 'C'; mapping 'B' values to 'C' values
B_to_C_Short = {
'P': 'P',
('A', 'F', 'H', 'R', 'None', 'F'): 'N'
}
键为A列与B列中的值组成的元组。
# 'A' & 'B' multi index in the format of tuple
MultiIndex = data.groupby(['A', 'B']).agg('sum').index.to_list() #
'''
print(len(MultiIndex))
53
print(MultiIndex)
[('AR', 'F'), ('BW', 'P'), ('CW', 'P'), ...]
'''
键为A列与B列中的值组成的元组,值为经过字典A和字典B映射后理应被映射到C列中相应的值。
# based on tuple values in 'A' col and 'B' col, and user define dicts,
# get a A & B col to C col mapping dict
MultiIndex_to_C_Full = {}
for i in MultiIndex: # i, e.g. ('AR', 'F')
for j in A_to_C_Short: # j, e.g. ('Y', ...)
for k in B_to_C_Short: # k, e.g. ('A', 'F', 'H', 'R', 'None', 'F')
if k == 'P':
if i[1] == k and i[0] in j:
MultiIndex_to_C_Full[i] = A_to_C_Short[j]
else:
if i[1] in k and i[0] not in j:
MultiIndex_to_C_Full[i] = B_to_C_Short[k]
'''
print(len(MultiIndex_to_C_Full))
53
pprint(MultiIndex_to_C_Full)
{('AR', 'F'): 'N',
...
('Y', 'P'): 'P',
'''
经过完整字典将基于A和B列中的值映射到C列中相应的值。
data['C'] = data[['A', 'B']].apply(lambda x: MultiIndex_to_C_Full.get((x.A, x.B)), axis=1)
'''
A Num ... B C
...
3 Y 962 ... P P
...
566 t 193 ... F N
'''
写此文时有借鉴以下资源
…
参见Python | Pandas | 多索引 | 自定义排序