Home > Software design >  Pandas Dataframe Invalid Key
Pandas Dataframe Invalid Key

Time:10-24

df[(df['Original Price'] != '0') & (df['Old Original Price'] != '0'), 'Price Difference'].index = df['Original Price'] - df['Old Original Price']

I am currently trying to compare two columns of the dataframe and if their value is not = to 0 they will make a new column and do a subtraction between the two values

although i seem to keep obtaining the error mentioned below

TypeError: '(Series([], dtype: bool), 'Price Difference')' is an invalid key

CodePudding user response:

You can try:

df.loc[((df['Original Price'] != '0') & (df['Old Original Price'] != '0')),'Price_Difference'] = df['Original Price'] - df['Old Original Price']

CodePudding user response:

I need to see a sample of how your data looks, and what are the data types of your columns, but based on what you mentioned, here is what I suggest:

df['Price Difference']= df['Original Price']
df.loc[((~df['Original Price'].isin(['0'])) & (~df['Old Original Price'].isin(['0']))), 'Price Difference']= df['Original Price'] - df['Old Original Price']

CodePudding user response:

Try this

df[Price Difference] =df.apply(function,axis=1)

And write logic in method

function(row):
    {
    if (row['Original Price'] != '0') & (row['Old Original Price'] != 
     '0'):
     return row['Original Price'] - row['Old Original Price']
     } 
  • Related