如何使用字典列表建立 Pandas DataFrame?


DataFrame 是一個二維的 Pandas 資料結構,用於以行和列格式表示表格資料。

我們可以使用 Python 字典列表建立 Pandas DataFrame 物件。如果我們將字典用作 DataFrame 函式的資料,則無需顯式指定列名。

下面我們將使用字典列表建立一個 DataFrame,請參見以下示例。

示例

# Creating list of dictionaries
li = [{'i': 10, 'j': 20, 'k': 30},{'i': 8, 'j': 40, 'k': 60},{'i': 6, 'j': 60, 'k': 90}]

# creating dataframe
df = pd.DataFrame(l, index=[100,101,102])

#display the output
print(df)

解釋

列表 li 包含一個字典列表,其中每個字典的鍵表示為列標籤,字典的值表示為 DataFrame 的資料(值)。如果要更改預設的行標籤,則可以使用 index 引數,如上例所示。

輸出

      i   j   k
100  10  20  30
101  8   40  60
102  6   60  90

上面程式碼塊顯示了 DataFrame 物件“df”的輸出,列標籤由字典鍵自動獲取,行標籤透過使用 index 引數定義。

示例

# Creating list of dictionaries
li = [{'A':10, 'B':89, 'C':43},{'A': 88, 'J': 50, 'B': 7},{'A':9, 'B':8, 'C':12}]


# creating dataframe
df = pd.DataFrame(li)

#display the output
print(df)

解釋

在以下示例中,字典列表中的鍵不相同,因此在生成的 DataFrame 物件中將得到缺失資料作為元素。

輸出

    A   B     C    J
0  10  89  43.0   NaN
1  88   7   NaN  50.0
2   9   8  12.0   NaN

在上面的 DataFrame 物件中可以看到 NaN 值。因為字典列表中沒有為列 J 定義資料。

更新於: 2021-11-18

2K+ 次檢視

開啟您的 職業生涯

透過完成課程獲得認證

開始學習
廣告

© . All rights reserved.