Home > other >  Using Pandas df.loc
Using Pandas df.loc

Time:10-05

I have a DataFrame of a csv file which is being read by pandas. What I am attempting to do is use df.loc to add a new column but only insert values into the column when values from another column, called "SKU" end with "-RF" and "-NEW".

The code I was working on is below. It has the csv file being read, "original_file", and then two .loc commands. ONE new column called "Cond" is supposed to be being added, and I want "NEW" to be added to that column where the value in the 'SKU' column ends with "-NEW" and "USED" to be added to the new column where the 'SKU' ends with "-RF".

AttributeError: 'list' object has no attribute 'str'

This is the error I have been getting on it.

original_file = pd.read_csv('wc-product-export-20-9-2022-1663680891149.csv')

original_file.loc[['SKU'].str.endswith("-RF"),'Cond'] = 'USED'
original_file.loc[['SKU'].str.endswith("-NEW"),'Cond'] = 'NEW'

CodePudding user response:

Try with adding the df when you call column by name

original_file.loc[original_file['SKU'].str.endswith("-RF"),'Cond'] = 'USED'

CodePudding user response:

Hope this is what you are looking for. You can use the apply function to check every cell in the SKU column and insert into the new column accordingly.

original_file['NEWCOL'] = original_file['SKU'].apply(
    lambda x: 'USED' if x.endswith('-RF') else 'NEW' if x.endswith('-NEW') else None)
  • Related