Python BOT 從 Excel 工作表中提取長列並建立一個資料框來對另一個文件中的一些數字進行編目

WBOY
發布: 2024-02-10 18:00:06
轉載
718 人瀏覽過

Python BOT 从 Excel 工作表中提取长列并创建一个数据框来对另一个文件中的一些数字进行编目

問題內容

我需要建立一個Python 機器人,從Excel 檔案1、工作表1 中提取C 列,並在檔案2 中進行編目,並計算從0.00 到0.99、從1.00 到1.99 等的數字總和。 12. 所有 12 以上的數字都編入最後一行。然後我需要計算所有數字的總和。

我嘗試編寫一些程式碼,但它沒有在 Excel 文件上寫入任何內容。


正確答案


您可以嘗試以下方法;

  1. #讀取 excel 資料檔(excel 檔 1),只選擇所需的列(「c 列」)。
  2. 建立值0.00 - 0.99、1.00 - 1.99、2.00 - 2.99、3.00 - 3.99(最多12 個)的數組,並使用它建立一個新資料幀(df_write),將資料幀中的值分組到數組範圍內。取得每個範圍的計數。
  3. 對大於 12 的值進行計數,並將其作為新行新增至 df_write。
  4. 對資料幀中的所有值求和,並將其作為新行新增至 df_write。
  5. 將資料框寫入 excel。在範例中,xlsxwriter 用作引擎,這表示每次執行程式碼時都會建立/覆蓋工作簿(目錄檔案)。
  6. 表格中可以包含其他資料/格式。例如,更改儲存格中的文字並新增公式來計算所有分組範圍值的總數,該總數應等於從 excel 資料檔案(datafile)讀取的總行數。
import pandas as pd

datafile = "Excel File 1.xlsx"
catalogfile = 'Excel File 2.xlsx'
column = 'column C'

### Read specific column (column) from Excel Sheet
df_read = pd.read_excel(datafile, index_col=None, na_values=['NA'], usecols=[column])
# print(df_read)

### Create the dataframe of values within specified ranges to write to Excel
### Group ranges 0.00 - 0.99 in increments of 1 and make a count of each up to a max (12)
df_write = df_read.groupby(pd.cut(df_read[column], [float(i) - 0.01 for i in range(0, 13)])).count()

### Count values greater than 12 and add as row to the dataframe
df_write.loc['12+'] = df_read[df_read > 12].count()

### Sum all values in the column and add as row to the dataframe
df_write.loc[len(df_write.index) + 1] = df_read.sum()

### Rename Index Header
df_write.index.name = 'Range Totals'
### Rename Column Header
df_write.columns = ['Values Count']

### Write dataframe to Excel
### Using default engine Xlsxwriter so new workbook is created (any existing workbook is overwritten)
with pd.ExcelWriter(catalogfile) as writer:
    df_write.to_excel(writer, sheet_name='Sheet1', index=True)

    ### Xlsxwriter formatting
    workbook = writer.book
    cell_format = workbook.add_format()
    cell_format.set_bold(True)

    ws = writer.sheets['Sheet1']
    ### Rename Row Header and add formula to count the totals for each range 
    ### (should equal the total number of data rows read from Excel)
    ws.write(df_write.size, 0, 'Column Total', cell_format)
    ws.write_row(df_write.size + 1, 0, ['Total Rows', '=SUM(B2:B14)'], cell_format)

    ws.autofit()
登入後複製

對於從資料檔案讀取的包含 100 行資料(即排除 hader)的列,excel 工作表的外觀範例。
「範圍總計」欄位是資料框中的索引列。範圍文字由資料框決定,但實際上涵蓋範圍 0.00 - 0.99、1.00 - 1.99、2.00 - 2.99、3.00 - 3.99 等。
如果需要,在寫入excel 時可以從資料框中刪除索引列,並使用xlsxwriter 將自訂文字寫入列,或使用具有現有標題的範本(在這種情況下,excelwriter 需要附加模式和openpyxl 作為引擎寫入現有工作簿)。

#

以上是Python BOT 從 Excel 工作表中提取長列並建立一個資料框來對另一個文件中的一些數字進行編目的詳細內容。更多資訊請關注PHP中文網其他相關文章!

來源:stackoverflow.com
本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板
關於我們 免責聲明 Sitemap
PHP中文網:公益線上PHP培訓,幫助PHP學習者快速成長!