Pandas convert pairs of values into new values
Question:
I have a pandas column that looks like this:
gender
0 1
1 2
2 1
3 1
4 3
5 2
6 1
7 4
8 5
9 1
I want all the values of 1 to stay 1, 2 or 5 to become 2, and 3 or 4 to become 3. The desired output would then be
gender
0 1
1 2
2 1
3 1
4 3
5 2
6 1
7 3
8 2
9 1
Would I just use if statements for this?
Answers:
Use replace
, you only need to map the values that change (5->2 and 4->3):
df['gender'] = df['gender'].replace({5: 2, 4: 3})
Output:
gender
0 1
1 2
2 1
3 1
4 3
5 2
6 1
7 3
8 2
9 1
I have a pandas column that looks like this:
gender
0 1
1 2
2 1
3 1
4 3
5 2
6 1
7 4
8 5
9 1
I want all the values of 1 to stay 1, 2 or 5 to become 2, and 3 or 4 to become 3. The desired output would then be
gender
0 1
1 2
2 1
3 1
4 3
5 2
6 1
7 3
8 2
9 1
Would I just use if statements for this?
Use replace
, you only need to map the values that change (5->2 and 4->3):
df['gender'] = df['gender'].replace({5: 2, 4: 3})
Output:
gender
0 1
1 2
2 1
3 1
4 3
5 2
6 1
7 3
8 2
9 1