簡體   English   中英

如何使用 Pandas 將字典導出到 excel

[英]How to export a dictionary to excel using Pandas

我正在嘗試使用 Pandas 將一些數據從 python 導出到 excel,但沒有成功。 數據是一個字典,其中的鍵是 4 個元素的元組。

我目前正在使用以下代碼:

df = pd.DataFrame(data)
df.to_excel("*file location*", index=False)

我得到一個導出的 2 列表,如下所示:

在此處輸入圖像描述

我正在嘗試獲取 excel 表,其中鍵的前 3 個元素被拆分為它們自己的列,鍵的第 4 個元素(在本例中為句點)成為列名,類似於下面的示例:

在此處輸入圖像描述

我已經嘗試對上面的代碼使用不同的添加,但我對此有點陌生,所以到目前為止沒有任何工作

根據您向我們展示的內容(不可復制),您需要pandas.MultiIndex

df_       = df.set_index(0)  # `0` since your tuples seem to be located at the first column
df_.index = pd.MultiIndex.from_tuples(df_.index)  # We convert your simple index into NDimensional index                 

# `~.unstack` does the job of locating your periods as columns 
df_.unstack(level=-1).droplevel(0, axis=1).to_excel(
    "file location", index=True
)

您可以嘗試導出到 csv

df.to_csv(r'Path where you want to store the exported CSV file\File Name.csv', index = False)

然后可以輕松地將其轉換為 excel 文件

暫無
暫無

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

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