简体   繁体   English

使用 Python 读取和打印 Excel 中的多个列表

[英]Reading and printing multiple lists in Excel using Python

I have 3 different columns of data that I am trying to organize and print.我有 3 个不同的数据列,我正在尝试组织和打印。 The excel file looks like: excel 文件如下所示:

在此处输入图像描述

I am trying to read the data into Python and my end goal is to print the data in the following way:我正在尝试将数据读入 Python ,我的最终目标是按以下方式打印数据:

Red: tshirt - 32, pants - 16, socks - 1
Blue: flannel - 48, pants - 23, socks - 5
Yellow: tshirt - 12

I organized all the columns into their own lists but the part I cannot figure out is how to instruct my program how to organize the items under the color heading since the color column only has 3 values.我将所有列组织到它们自己的列表中,但我无法弄清楚的部分是如何指导我的程序如何组织颜色标题下的项目,因为颜色列只有 3 个值。 For example, how can I tell the program that tshirt, pants, and socks are under the red color heading and tshirt is under the yellow color heading?例如,我如何告诉程序 T 恤、裤子和袜子在红色标题下,而 T 恤在黄色标题下? Is there a way to generalize this so it can read and sort this information on other spreadsheets of the same format?有没有办法概括这一点,以便它可以在相同格式的其他电子表格上读取和排序这些信息?

You could try this, using pandas.read_excel() , pandas.fillna() and pandas.groupby() :你可以试试这个,使用pandas.read_excel()pandas.fillna()pandas.groupby()

import pandas as pd

df = pd.read_excel('Book1.xlsx',header=None)
df=df.fillna(method='ffill').groupby(0).agg(list)
print(df)


for idx,color in enumerate(df.index):
    line=str(color)+': '
    for cloth,value in zip(df.iloc[idx,0],df.iloc[idx,1]):
        line+=str(cloth)+' - '+str(value)+', '
    print(line[:len(line)-2])

Output: Output:

df:

                              1            2
0                                           
Blue    [flannel, pants, socks]  [48, 23, 5]
Red       [tshirt, pants, sock]  [32, 16, 1]
Yellow                 [tshirt]         [12]

#Desired Output
Blue: flannel - 48, pants - 23, socks - 5
Red: tshirt - 32, pants - 16, sock - 1
Yellow: tshirt - 12

Edit:编辑:

Using openpyxl and is_color_like :使用openpyxlis_color_like

import openpyxl as opx
from matplotlib.colors import is_color_like
workbook = opx.load_workbook(r'Book1.xlsx', read_only=True)
first_sheet = workbook.worksheets[0]

fstr=''
for i in range(first_sheet.max_row):
    for j in range(first_sheet.max_column):
        if first_sheet.cell(row=i+1, column=j+1).value!=None:
            s=first_sheet.cell(row=i+1, column=j+1).value
            if is_color_like(s) and not all(map(str.isdigit, s)):
                fstr+='\n'+s+': '
            elif isinstance(s, int):
                fstr+=str(s)+', '
            else:
                fstr+=s+' - '
            


print(fstr[:len(fstr)-2])

Output: Output:

Red: tshirt - 32, pants - 16, sock - 1, 
Blue: flannel - 48, pants - 23, socks - 5, 
Yellow: tshirt - 12

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM