我正在尝试将B 列的值i动态替换为一致的值,条件是A 列中j的值计数。我正在尝试使用字典来映射值,但它不起作用。color = ['black','mauve','teal','green','teal','black']code = ['E45', 'M46', 'Y76', 'G44', 'T76','B43']df = pd.DataFrame({'color': color, 'code': code})# Dedupe a copydf_copy = dfdf_copy = df_copy.drop_duplicates(subset='color', keep='first')# Create a dictionarydummy_dict = df_copy[['color','code']].to_dict('list')# {'color': ['black', 'mauve', 'teal', 'green', 'teal', 'black'], 'code': ['E45', 'M46', 'Y76', 'G44', 'T76', 'B43']}### Not workingdf["new_code"] = df.code.replace(dummy_dict)### Output (wrong):# color code new_code# black E45 E45# mauve M46 M46# teal Y76 Y76# green G44 G44# teal T76 T76# black B43 B43### Desired output:# color code new_code# black E45 E45# mauve M46 M46# teal Y76 Y76# green G44 G44# teal T76 Y76# black B43 E45我哪里错了?就好像 Python 甚至没有访问我的字典来映射值。
1 回答
慕少森
TA贡献2019条经验 获得超9个赞
它是transform和first
df['new_code'] = df.groupby('color').code.transform('first')
Out[21]:
color code new_code
0 black E45 E45
1 mauve M46 M46
2 teal Y76 Y76
3 green G44 G44
4 teal T76 Y76
5 black B43 E45
添加回答
举报
0/150
提交
取消