0

I am still new to python and I need help.

I have several csv files. One of them look like this:

test.csv

Name,Colour,ID
Fiona,Brown,23
Alex,Brown,24
Mary,Pink,25
Jane,Yellow,26
John,Pink,27
Emma,Yellow,28

And another file looks like this:

test2.csv

Name,Colour,ID
Gwen,Black,29
Peter,Brown,30
Stranger,Black,31
Abou,Yellow,32
Jonah,Yello,33
Kim,Yellow,34

I'm trying to check if a certain colour exist in the file and extract its row.

Here is what i've tried.

import pandas as pd

#User input file name
filename = input("Enter file name: ")


#Open and read CSV file
file = pd.read_csv(filename + ".csv")

#Check if black exist or not
if 'Black' in file:
    bl = file.loc["Black"]
    print("Yes")
else:
    print("No Black")


if 'Brown' in file:
    Brown = file.loc["Brown"]
    print(Brown)
else:
    print("No brown")


if 'Pink' in file:
    Pink = file.loc["Pink"]
    print(Pink)
else:
    print("No Pink")


if 'Yellow' in file:
    Yellow = file.loc["Yellow"]
    print(Yellow)
else:
    print("No Yellow")

This is the output that I get when I run my code

Enter file name: test
No Black
No brown
No Pink
No Yellow

Is there any suggestion so that I can get the output correctly?

2 Answers 2

1

file is a dataframe. If you do if 'Black' in file it will only search the column names (which are ['Name', 'Colour', 'ID']).

You need to be more specific about where you want to search (i.e. which column to search).

To find 'black' in the colour column use:

if 'black' in file['Colour'].values:
    bl = file.loc[file['Colour'] == "Black"]
    print("Yes")
Sign up to request clarification or add additional context in comments.

Comments

1

You have to convert this column (Series) to list if you want to use in statement:

COLORS = ['Black', 'Brown', 'Pink', 'Yellow']

filename = input('Enter file name: ')
df = pd.read_csv(f'{filename}.csv')


colors = df['Colour'].tolist()

for color in COLORS:
    print(f'{color}' if color in colors else f'no {color}')

Output:

Enter file name: test
no Black
Brown
Pink
Yellow

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.