1
$\begingroup$

Suppose I have a data like this:

enter image description here

and I want to change the value of name and gender into an integer, and I have a dictionary like this:

enter image description here

I understand that I can use replace function in pandas, but I don't know how to use an excel dictionary to replace the value

thank you

$\endgroup$

1 Answer 1

1
$\begingroup$

Assuming you have a pair of csv files: "replace.csv" representing the first table and "table.csv" representing the second table i.e. "dict". Use the following code:

import pandas as pd

frame = pd.read_csv('replace.csv')
table = pd.read_csv('table.csv', header=None)

mapping = dict([(k, v) for k, v in table.values])

frame.replace(to_replace={"name": mapping, "gender": mapping}, inplace=True)
print frame

The line mapping = dict([(k, v) for k, v in table.values]) is the one that transforms your dataframe into a dict. For more on transforming a dataframe into a dictionary see the documentation, also this question provides different ways of transforming a dataframe into a dictionary. For reading excel files, instead of csv files, see this.

$\endgroup$

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.