如何使用字典列表建立 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 定義資料。
廣告
資料結構
網路
關係型資料庫管理系統
作業系統
Java
iOS
HTML
CSS
Android
Python
C 語言程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP