0

I have a dataframe like this:

code_0101    code_0102    code_0103    code_0104    ...
0            1            2            3            ...
...          ...          ...          ...

I also have a dictionary:

{'0101': 'cirurgical_procedures', '0102': 'medical_care', '0103': 'remedy', ...}

I want to apply a regex to dataframe column and replace the code numbers accorging to my dictionary, and get something like this:

code_cirurgical_procedures    code_medical_care       ...
0                             1                       ...
...                           ...

How can I do these two steps, specially the second, about the dictionary?

2 Answers 2

3

Use series.replace to replace and assign back to columns

d = {'0101': 'cirurgical_procedures', '0102': 'medical_care', '0103': 'remedy'}
df.columns = df.columns.to_series().replace(d, regex=True)

Out[12]:
   code_cirurgical_procedures  code_medical_care  code_remedy  code_0104
0                           0                  1            2          3
Sign up to request clarification or add additional context in comments.

Comments

1

Assuming code as perfix you can use a dict comprehension,

 cols = {'0101': 'cirurgical_procedures', '0102': 'medical_care', '0103': 'remedy'}

df.rename(columns = {f"code_{k}": f"code_{v}" for k,v in cols.items()})

2 Comments

Thank you! First time seeing a dict comprehension
But just for curiosity, if the preffix isn't the same in every column, what could I do?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.