Home > database >  How can I modify a variable in a dataframe using a If condition?
How can I modify a variable in a dataframe using a If condition?

Time:10-13

I would like to replace some variable using the IF condition. For exemple I have this dataframe :

Name New_Name Flag_Name
NK Nike 1
ADD Adidas 1
Microsoft Microsoft 0
APP Apple 1

If the Flag_Name = 1 then I have to replace the Name column by the content of the New_Name column, and if the Flag_Name = 0 then keep the content of the Name column.

Thanks for your help

CodePudding user response:

Try loc:

df.loc[df['Flag_Name'] == 1, 'Name'] = df['New_Name']

Or with a mask:

m = df['Flag_Name'] == 1
df.loc[m, 'Name'] = df.loc[m, 'New_Name']

Or df['Name'].where:

df['Name'] = df['Name'].where(df['Flag_Name'] == 1, df['New_Name'])

CodePudding user response:

Can also use np.where:

df['Name'] = np.where(df['Flag_Name'] == 1, df['New_Name'], df['Name'])

Output:

        Name   New_Name  Flag_Name
0       Nike       Nike          1
1     Adidas     Adidas          1
2  Microsoft  Microsoft          0
3      Apple      Apple          1

CodePudding user response:

you can also try a function and work with more than one conditional.

First it's a good practice put the columns name in lower case and clean it, assuming that maybe there are spaces in it , then you can avoid errors.

One of the ways you can do that is with a list comprehension.

cols =[col.strip().lower() for col in df.columns]
df.columns = cols

Output

name new_name flag_name
NK Nike 1
ADD Adidas 1
Microsoft Microsoft 0
APP Apple 1

Ok! Now Let's work with the replacement. For that let's create a function that will iterate over the Dataframe.

def correctname(df,col): #we need to pass the Dataframe name and the column to check
     for i, row in df.iterrows():
         conditional =row[col] #here we have the value to check
         if conditional == 1:
         df.iloc[i,0]=df.iloc[i,1]# the 0 and 1 are the index columns 'name' and 'new_name'

correctname(df,'flag_name')

df

Output

name new_name flag_name
Nike Nike 1
Adidas Adidas 1
Microsoft Microsoft 0
Apple Apple 1
  • Related