[英]Reading and printing multiple lists in Excel using Python
我有 3 個不同的數據列,我正在嘗試組織和打印。 excel 文件如下所示:
我正在嘗試將數據讀入 Python ,我的最終目標是按以下方式打印數據:
Red: tshirt - 32, pants - 16, socks - 1
Blue: flannel - 48, pants - 23, socks - 5
Yellow: tshirt - 12
我將所有列組織到它們自己的列表中,但我無法弄清楚的部分是如何指導我的程序如何組織顏色標題下的項目,因為顏色列只有 3 個值。 例如,我如何告訴程序 T 恤、褲子和襪子在紅色標題下,而 T 恤在黃色標題下? 有沒有辦法概括這一點,以便它可以在相同格式的其他電子表格上讀取和排序這些信息?
你可以試試這個,使用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:
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
和is_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:
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.