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

2024-09-26 18:11:23 发布

您现在位置:Python中文网/ 问答频道 /正文

我有3列不同的数据,我正试图组织和打印。excel文件如下所示:

enter image description here

我正在尝试将数据读入Python,我的最终目标是以以下方式打印数据:

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

我将所有列组织到它们自己的列表中,但我无法理解的部分是如何指导我的程序如何组织颜色标题下的项目,因为颜色列只有3个值。例如,我如何告诉程序T恤、裤子和袜子在红色标题下,而T恤在黄色标题下?有没有一种方法可以概括这一点,这样它就可以在相同格式的其他电子表格上读取和排序这些信息


Tags: 文件数据程序标题颜色方式bluered
1条回答
网友
1楼 · 发布于 2024-09-26 18:11:23

您可以尝试使用^{}^{}^{}

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])

输出:

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

编辑:

使用openpyxl^{}

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])

输出:

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

相关问题 更多 >

    热门问题