Note: Before executing, create an example.csv file containing some names and gender
Let’s say we have a table with names and genders. There are two categories in the gender column, male and female, and suppose we want to assign 1 male and 2 female.
Examples:
Input: -------- ------------- | Name | Gender --------------------- 0 Ram Male 1 Seeta Female 2 Kartik Male 3 Niti Female 4 Naitik Male Output: | Name | Gender --------------------- 0 Ram 1 1 Seeta 2 2 Kartik 1 3 Niti 2 4 Naitik 1
Method 1:
To create a dictionary containing two elements with following key-value pair: Key Value male 1 female 2
Then repeat the for loop on the Gender column of the object DataFrame and replace the values where the keys are.
|
Output:
| Name | Gender --------------------- 0 Ram 1 1 Seeta 2 2 Kartik 1 3 Niti 2 4 Naitik 1
Method 2:
Method 2 is also similar, but does not require a dictionary file and takes fewer lines of code. In this, we internally iterate over the Gender DataFrame column and change the values if the condition matches.
|
Output:
| Name | Gender --------------------- 0 Ram 1 1 Seeta 2 2 Kartik 1 3 Niti 2 4 Naitik 1
Applications
- This method can be applied in data science. Suppose that if we are working with a dataset that contains gender as "male" and "female", then we can assign numbers, for example, "0" and "1" respectively, so that our algorithms can work with the data. Li>
- This method can also be used to replace some specific values in datasets with new values.
References