0

How do you do add all matching cell values to a list with Pandas?

Excel File Example, Search for Color[Red], append Fruit into fruit_names = {}

Fruit_ID      Color    Weight   Fruit
1             Red      5lbs     Apple
2             Orange   2lbs     Orange
3             Red      3lbs     Strawberry  


import pandas as pd
import os

os.chdir("/users/user/folder/helloworld")
name_list = ["Sheet1"]

fruit_names = {}

def fruit_colors(file):
    data = pd.read_excel(file, sheet_name = name_list[0])
    for row in data:
            print(format(row[0].value, row[1].value).append(fruit_names))
    print(fruit_names)

        

1 Answers1

1

I'm not sure if this is what you want. you can use df[df['color'] == 'selected color'] to get the fruits you want

you can check it here

How to select rows from a DataFrame based on column values

fruit_names = []
df = pd.read_excel(file)
red_fruits = df[df['Color'] =='Red']['Fruit'].values
fruit_names.append(red_fruits)

sammy
  • 427
  • 1
  • 3
  • 14
  • Why am I getting an Index Out of Range error when printing fruit_names[1] but not fruit_names[0]? It seems everything was grouped into fruit_names[0]? – peachesyerp Dec 09 '20 at 04:20
  • 1
    by doing `df[df['Color'] =='Red']['Fruit'].values`, you will get a list of values with `color==red`. You can just use `red_fruits` if you're not going to look for other colors – sammy Dec 09 '20 at 05:44