簡體   English   中英

如何在Python中將字典輸出到Excel工作表

[英]How to output my dictionary to an Excel sheet in Python

背景:我的第一個與Excel相關的腳本。 使用openpyxl。 有一個Excel工作表,其中包含有關不同列中產品的不同類型數據的負載。

我的目標是從某些列中提取某些類型的數據(例如價格,條形碼,狀態),將這些數據分配給唯一的產品代碼,然后將產品代碼,價格,條形碼和狀態輸出到新的excel文檔。

我已成功提取數據並將其放入以下字典格式:

productData = {'AB123': {'barcode': 123456, 'price': 50, 'status': 'NEW'}

我對將輸出結果輸出到新報告中的一般想法是這樣的(盡管我知道這是錯誤的):

newReport = openpyxl.Workbook()
newSheet = newReport.active
newSheet.title = 'Output'

newSheet['A1'].value = 'Product Code'
newSheet['B1'].value = 'Price'
newSheet['C1'].value = 'Barcode'
newSheet['D1'].value = 'Status'

for row in range(2, len(productData) + 1):
    newSheet['A' + str(row)].value = productData[productCode]
    newSheet['B' + str(row)].value = productPrice
    newSheet['C' + str(row)].value = productBarcode
    newSheet['D' + str(row)].value = productStatus

newReport.save('ihopethisworks.xlsx')

我實際上需要做什么來輸出數據?

我建議為此使用熊貓。 它具有以下語法:

df = pd.read_excel('your_file.xlsx')
df['Column name you want'].to_excel('new_file.xlsx')

您可以用它做更多的事情。 Openpyxl可能不是適合您的任務的工具(Openpyxl太籠統了)。

PS:我將在評論中保留此內容,但出於他們的智慧,stackoverflow決定讓任何人留下答案,但不發表評論。

您提取數據所使用的邏輯丟失了,但是我懷疑最好的方法是使用它來並行遍歷兩個工作表。 然后,您可以避免完全使用字典,而只需將循環附加到新工作表即可。

偽代碼:

ws1 # source worksheet
ws2 # new worksheet

product = []
code = ws1[…] # some lookup
barcode = ws1[…]
price = ws1[…]
status = ws1[…]

ws2.append([code, price, barcode, status])

熊貓在這方面最有效

import pandas as pd

#df columns:  Date    Open    High     Low   Close     Volume
#reading data from an excel 
df = pd.read_excel('GOOG-NYSE_SPY.xls')

#set index to the column of your choice, in this case it would be date
df.set_index('Date', inplace = True)

#choosing the columns of your choice for further manipulation
df = df[['Open', 'Close']]

#divide two colums to get the % change
df = (df['Open'] - df['Close']) / df['Close'] * 100


print(df.head())

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM