如何使用字典建立 Pandas DataFrame?


DataFrame 用於以二維資料表格式表示資料。與資料表相同,Pandas DataFrame 也具有行和列,並且每列和每行都用標籤表示。

透過使用 Python 字典,我們可以建立自己的 Pandas DataFrame,這裡字典的鍵將成為列標籤,值將是行資料。

在這裡,我們將使用 Python 字典建立一個 DataFrame,讓我們看看下面的示例。

示例

# importing the pandas package
import pandas as pd

data = {"int's":[1, 2, 3, 4],
"float's":[2.4, 6.67, 8.09, 4.3]}

# creating DataFrame
df = pd.DataFrame(data)

# displaying resultant DataFrame
print(df)

解釋

變數 data 包含一個 Python 字典物件,其中包含鍵值對,這裡字典的鍵表示為列標籤,字典的值表示為結果 DataFrame 中的行資料。

在給定的字典中,鍵具有字串資料“int's、float's”,字典的值載入了列表整數和浮點數。

輸出

   int's   float's
0     1     2.40
1     2     6.67
2     3     8.09
3     4     4.30

上面程式碼塊顯示了 'df' DataFrame 物件的輸出,正如我們所看到的,列標籤“int's、float's”來自字典鍵,DataFrame 中的值取自資料變數的字典值。

示例

# importing the pandas package
import pandas as pd

data = {'B':'Black',
'W':'White',
'R':'Red',
'G':'Green'}

# creating DataFrame
df = pd.DataFrame(data, index=['Colors'])

# displaying resultant DataFrame
print(df)

解釋

在以下示例中,字典 'data' 僅具有標量值,因此我們需要顯式地提及索引標籤。如果我們沒有提及索引值,則會引發“ValueError”。並且字典中的鍵將預設成為列標籤。

輸出

          B     W   R     G
Colors Black White Red Green

上面的 DataFrame 物件有一行和四列。

更新於: 2021-11-17

717 次瀏覽

開啟您的 職業生涯

透過完成課程獲得認證

開始學習
廣告

© . All rights reserved.