Home > database >  How to put 1 or 2 in A column according to the value of column B?
How to put 1 or 2 in A column according to the value of column B?

Time:08-24

For example, if house column is "Own" (it is string), than I want to put 1 to tax_home. How can I make code for it?

I tried this code but it doesn't work. Help me

def none(x):
    if df1['house'] = "Own":
        return df1['tax_home'] = 1
    else:
        return 0

df1['tax_home1'] = df1['house'].apply(none)

CodePudding user response:

You can simply do:

df['tax_home'] = (df['home'] == 'Own').astype(int)

This solution uses numpy vectorization to avoid an unnecessary for loop.

CodePudding user response:

Suppose you have:

df = pd.DataFrame({'home':['own','own','rental','rental','own']})

Then you can:

df['tax_home'] = df['home'].apply(lambda row: 1 if row=='own' else 0)

CodePudding user response:

First I would define a function that is not named none for easier to understand that it is actually a function. Then you have to use the argument in the function now called house. Then return values based on a proper if statement using ==.

def set_tax_home(house): 
   if house == "Own": 
      return 1 
   else: 
      return 0

df1['tax_home'] = df1['house'].apply(set_tax_home)
  • Related