簡體   English   中英

如何從excel鏈接熊貓中的分層數據?

[英]How to link hierarchical data in pandas from excel?

我有這個 excel 表,其層次結構如下: excel 片段

Item Category Price
**Electronics** 1 
Laptop 1 1000
Kindle 1 200
Mobile 1 500
**HouseItems** 2
VacuumCleaner 2 200
Clock 2 50

我如何按類別獲取項目? 例如,獲取筆記本電腦等電子產品及其價格,並在單獨的列表中獲取家居用品。 在excel表中我有更多的類別,這只是一個片段。


df = pd.read_excel('items.xlsx',
                   ['itemSheet'], engine='openpyxl')
df['items'] = pd.Series()
item_list= ['Electronics', 'HouseItems']
for item in df['itemSheet']['Item']:
    if item in cost_entry_group:
        df['items'].add(item)

print(df['items'])

我如何將 itemCategory(electronics) 鏈接到筆記本電腦、kindle 和手機以及它們各自的價格,並對家居用品做同樣的事情?

這個類別不是已經在你的 df 中了嗎?

使用df[df['Category'] == 1]來獲取類別等於 1 又名“HouseItems”的項目

您還可以執行以下操作:

categories = {'Electronics': 0, 'HouseItems': 1}
dfs  = {}
for category_name, category_number in categories.items():
     dfs[category_name] = df[df['Category'] == category_number]

獲取僅包含一個類別的多個 DataFrame。

要從 DataFrame 中提取類別,您可以檢查價格中的“nan”值:

categories = {}
for index, row in df.iterrows():
    if row.isnull().values.any():
        categories[row['Item']] = row['Category']

這將是我快速而骯臟的解決方案。 或者,您可以使用 openpyxl 瀏覽 Excel 表並檢查粗體文本:

from openpyxl import load_workbook

wb = load_workbook(path, data_only=True)
sh = wb[wb.sheetnames[0]]
categories = {}
for i in range(sh.min_row, sh.max_row): # go through rows
    if sh['A{}'.format(i)].font.b == True: # font.b gives True if bold otherwise False
        name = sh['A{}'.format(i)].value
        number = sh['B{}'.format(i)].value
        categories[name] = number

可能有“更好”的解決方案,但它有效。

暫無
暫無

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

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