pandas 使用字典将值输入 Dataframe 的Map

i86rm4rw  于 2022-12-25  发布在  其他
关注(0)|答案(2)|浏览(194)

我有一本字典,看起来像这样:{1:“A”,2:“B”,3:“C”}
和 Dataframe :
| 列_1|第二栏|
| - ------|- ------|
| 一、三、二||
| 1个||
| 二、三||
如何组织Map以获得以下结果:
| 列_1|第二栏|
| - ------|- ------|
| 一、三、二|A、C、B|
| 1个|A类|
| 二、三|B、C类|

jk9hmnmh

jk9hmnmh1#

这对我很有效

import pandas as pd
alphabet = ['A','B','C','D','E','F','G','H','I']#...
d = {1:"A", 2:"B", 3:"C"}
s = pd.Series([(1,2,3),1,1,3])
df = pd.DataFrame(s, columns = ["col1"])
col2 = pd.Series([ alphabet[i-1] if isinstance(i,int) else [alphabet[j-1] for j 
in i] for i in s ])
df2 = pd.DataFrame({"col1":s, "col2":col2}
xxe27gdn

xxe27gdn2#

通过dict.getMap使用嵌套列表解析-如果不匹配,则不替换:

d = {1:"A", 2:"B", 3:"C"}
df['col_2'] = [','.join(d.get(int(y), y) for y in x.split(',')) for x in df['col_1']]
print (df)
   col_1  col_2
0  1,3,2  A,C,B
1      1      A
2    2,3    B,C

字典中不存在值时的可能解决方案-第二个解决方案忽略不匹配的值(7):

print (df)
     col_1
0  1,3,2,7
1        1
2      2,3

d = {1:"A", 2:"B", 3:"C"}
df['col_2_1'] = [','.join(d.get(int(y), y) for y in x.split(',')) for x in df['col_1']]

df['col_2_2'] = [','.join(d.get(int(y)) for y in x.split(',') if int(y) in d) for x in df['col_1']]
print (df)
     col_1  col_2_1 col_2_2
0  1,3,2,7  A,C,B,7   A,C,B
1        1        A       A
2      2,3      B,C     B,C

相关问题