Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Using Pandas df.loc

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’

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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'

>Solution :

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)
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading