Bryan McCormack
Bryan McCormack

Reputation: 105

How to Use an If Statement with a DataFrame from Excel file?

I'm playing with some data from an Excel file. I imported the file, made it into a dataframe, and now want to iterate over a column named 'Category' for certain keywords, fine them, and retun another column ('Asin'). I'm having trouble finding the correct syntax to make this work.

the code below is my attempt at an if statement:

import pandas as pd
import numpy as np

file = r'C:/Users/bryanmccormack/Downloads/hasbro_dummy_catalog.xlsx'
xl = pd.ExcelFile(file)
print(xl.sheet_names)
df = xl.parse('asins')
df

check = df.loc[df.Category == 'Action Figures'] = 'Asin'
print(check)

Upvotes: 0

Views: 292

Answers (1)

dizzy77
dizzy77

Reputation: 543

Alex Fish provided the correct answer, if I understand the question.

To elaborate, df.loc[df.Category == 'Action Figures'] returns a data frame with the rows that meet the bracketed condition, so ['Asin'] at the end returns the "Asin" column from that data frame.

Fyi,

check = df.loc[df.Category == 'Action Figures'] = 'Asin'

This is a multiple assignment statement - that is,

a = b = 4

is the same as

b = 4
a = b

So your code is apparently rewriting some values of your data frame df, which you probably don't want.

Upvotes: 1

Related Questions