首页 > 解决方案 > 如何将匹配的单元格值附加到列表中?

问题描述

如何使用 Pandas 将所有匹配的单元格值添加到列表中?

Excel 文件示例,搜索 Color[Red],将 Fruit 添加到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)

        

标签: python

解决方案


我不确定这是否是你想要的。你可以df[df['color'] == 'selected color']用来得到你想要的水果

你可以在这里查看

如何根据列值从 DataFrame 中选择行

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


推荐阅读