1

I have one column called "A" with only values 0 or 1. I have another column called "B". If column A value=0, I want the column B value to equal "dog". If column A value=1, I want the column B value to equal "cat".

Sample DataFrame column:

print(df)
   A
0  0
1  1

Is there anyway to fill the B column as such without a for loop?

Desired:

print(df)
   A  B
0  0  Cat
1  1  Dog

Thanks

Karn Kumar
  • 8,518
  • 3
  • 27
  • 53
carsof
  • 83
  • 1
  • 8
  • What have you tried based on your own research, and what were your results? Please [edit] to include a [mcve] – G. Anderson Aug 02 '21 at 17:53
  • See [Change one value based on another value in pandas](https://stackoverflow.com/questions/19226488/change-one-value-based-on-another-value-in-pandas) – G. Anderson Aug 02 '21 at 17:54

2 Answers2

1

Can Simply can try Below using map...

Sample Data

print(df)
   A
0  0
1  1
2  0
3  1
4  1
5  1
6  0
7  0
8  1

Result:

df['B'] = df['A'].map({0:'Cat', 1:'Dog'})
print(df)
   A    B
0  0  Cat
1  1  Dog
2  0  Cat
3  1  Dog
4  1  Dog
5  1  Dog
6  0  Cat
7  0  Cat
8  1  Dog
Karn Kumar
  • 8,518
  • 3
  • 27
  • 53
0

Next time, please post your research and minimal reproducible code. See comments

import pandas as pd

d = {'A': [0, 1, 0]}
df = pd.DataFrame(data=d)
m = {0: ("Dog"), 1: ("Cat")}
df['B'] = df['A'].map(lambda x: m[x])
DarkFantasy
  • 240
  • 3
  • 16