如何在 Pandas 中將 DataFrame 轉換成字典?


要將 Pandas DataFrame 轉換為字典,我們可以使用 to_dict() 方法。我們舉個例子,看看它是如何實現的。

步驟

  • 建立二維、尺寸可變、可能是異構的表格資料 df
  • 列印輸入 DataFrame df
  • 使用 to_dict() 方法將 DataFrame 轉換為字典並打印出來。

示例

import pandas as pd

df = pd.DataFrame(
   {
      "x": [5, 2, 7, 0],
      "y": [4, 7, 5, 1],
      "z": [9, 3, 5, 1]
   }
)
print "Input DataFrame is:\n", df
print "Convert DataFrame into dictionary: \n", df.to_dict()

輸出

Input DataFrame is:
   x  y  z
0  5  4  9
1  2  7  3
2  7  5  5
3  0  1  1

Convert DataFrame into dictionary:
{'x': {0: 5, 1: 2, 2: 7, 3: 0}, 'y': {0: 4, 1: 7, 2: 5, 3: 1},
'z': {0: 9, 1: 3, 2: 5, 3: 1}}

更新於:14-9-2021

1K+ 瀏覽量

開啟您的 職業

透過完成課程獲得認證

開始
廣告
© . All rights reserved.