-1

it is necessary to create a column with the name according to their code. I have a dictionary, I'm trying to rename codes to titles. There are two conditions, because the code may not be in the dictionary, then you need to write the code, or if the code field is empty, then write the void.if there is only one code, everything works, if there are several codes, a problem arises

enter image description here enter image description here

I tried to write a lambda function

missing_values = {}
dict_=dict_name
dict_fr=pd.DataFrame.from_dict(dict_name, orient='index')
dict_fr.index=dict_fr.index.map(str)
for_ag_pivot['name_cod']=for_ag_pivot['cod_last'].apply(lambda x: ",".join(dict_fr[0].loc[str(x).split(',')].tolist() if x in dict_name.keys() else x))
wjandrea
  • 28,235
  • 9
  • 60
  • 81
  • The question is completely unclear. Maybe you would prefer to ask on [ru.so]? Otherwise, check out [ask] and [How to make good reproducible pandas examples](/q/20109391/4518341). Either way, [please don't post pictures of text](https://meta.stackoverflow.com/q/285551/4518341). – wjandrea Mar 30 '23 at 21:25

1 Answers1

0

You can try with .get in something like

getSingle = lambda l: l[0] if isinstance(l,list) and len(l)==1 else l
getName = lambda x: ','.join([getSingle(dict_name.get(c,c)) for c in x.split(',')])
for_ag_pivot['name_cod'] = for_ag_pivot['cod_last'].apply(getName)

If dict_name only contains values that are single-item lists, you don't need getSingle and getName can just be lambda x: ','.join([dict_name.get(c,[c])[0] for c in x.split(',')]).

Driftr95
  • 4,572
  • 2
  • 9
  • 21