Pandas DataFrames 是具有帶標簽的行和列的二維數(shù)據(jù)結(jié)構(gòu),可以存儲很多類型的數(shù)據(jù)。如果你熟悉 Excel 的話,可以將 Pandas DataFrames 看做類似于電子表格。
首先,我們將使用 Pandas Series 字典手動創(chuàng)建一個 DataFrame。第一步是創(chuàng)建 Pandas Series 字典。字典創(chuàng)建完畢后,我們可以將該字典傳遞給 pd.DataFrame() 函數(shù)。
我們將創(chuàng)建一個字典,其中包含 Alice 和 Bob 從在線商店中購買的商品。該 Pandas Series 將使用所買商品的價格作為數(shù)據(jù),所買商品作為索引標簽。我們來看看如何編寫代碼:
# We import Pandas as pd into Python
import pandas as pd
# We create a dictionary of Pandas Series
items = {'Bob' : pd.Series(data = [245, 25, 55], index = ['bike', 'pants', 'watch']),
'Alice' : pd.Series(data = [40, 110, 500, 45], index = ['book', 'glasses', 'bike', 'pants'])}
# We print the type of items to see that it is a dictionary
print(type(items))
class 'dict'
字典已經(jīng)創(chuàng)建完畢,我們可以通過將其傳遞給 pd.DataFrame() 函數(shù),創(chuàng)建 DataFrame。我們將創(chuàng)建一個可以表示多位用戶的購物車的 DataFrame,在此例中只有兩位用戶,即 Alice 和 Bob。
# We create a Pandas DataFrame by passing it a dictionary of Pandas Series
shopping_carts = pd.DataFrame(items)
# We display the DataFrame
shopping_carts
| Alice | Bob | |
|---|---|---|
| bike | 500.0 | 245.0 |
| book | 40.0 | NaN |
| glasses | 110.0 | NaN |
| pants | 45.0 | 25.0 |
| watch | NaN | 55.0 |
有幾個事項需要注意。我們發(fā)現(xiàn) DataFrame 以表格形式顯示,和 Excel 電子表格很像,行和列的標簽以粗體形式顯示。此外注意,DataFrame 的行標簽根據(jù)構(gòu)建字典所用的兩個 Pandas Series 的索引標簽創(chuàng)建而成。DataFrame 的列標簽來自字典的鍵。另一個注意事項是,列按照字母順序排序,而不是字典中的順序。稍后我們將發(fā)現(xiàn),當我們從數(shù)據(jù)文件中向 DataFrame 加載數(shù)據(jù)時,不會發(fā)生這種情況。最后要注意的是,我們發(fā)現(xiàn)該 DataFrame 中出現(xiàn)了一些 NaN 值。NaN 是指非數(shù)字,Pandas 通過這種方式表示該行和列索引沒有值。例如,如果我們查看 Alice 列,我們發(fā)現(xiàn)手表索引的值是 NaN。你可以通過查看一開始創(chuàng)建的字典,了解為何是這種情況??梢郧逦乜闯?,Alice 手表標簽沒有條目。因此,在創(chuàng)建 DataFrame 時,如果特定行索引的特定列沒有值,Pandas 將用 NaN 值填充。如果要將此數(shù)據(jù)饋送到機器學(xué)習算法中,我們首先需要刪掉這些 NaN 值。
在上述示例中,我們使用具有定義清晰的索引的 Pandas Series 字典創(chuàng)建了 Pandas DataFrame。如果我們不向 Pandas Series 提供索引標簽,Pandas 在創(chuàng)建 DataFrame 時將使用數(shù)字行索引。我們來看一個示例:
# We create a dictionary of Pandas Series without indexes
data = {'Bob' : pd.Series([245, 25, 55]),
'Alice' : pd.Series([40, 110, 500, 45])}
# We create a DataFrame
df = pd.DataFrame(data)
# We display the DataFrame
df
| Alice | Bob | |
|---|---|---|
| 0 | 40 | 245.0 |
| 1 | 110 | 25.0 |
| 2 | 500 | 55.0 |
| 3 | 45 | NaN |
可以看出,Pandas DataFrame 的行索引從 0 開始,就像 NumPy ndarray 的索引一樣。
現(xiàn)在,和 Pandas Series 一樣,我們也可以使用屬性從 DataFrame 中提取信息。我們輸出 shopping_carts DataFrame 中的一些信息
# We print some information about shopping_carts
print('shopping_carts has shape:', shopping_carts.shape)
print('shopping_carts has dimension:', shopping_carts.ndim)
print('shopping_carts has a total of:', shopping_carts.size, 'elements')
print()
print('The data in shopping_carts is:\n', shopping_carts.values)
print()
print('The row index in shopping_carts is:', shopping_carts.index)
print()
print('The column index in shopping_carts is:', shopping_carts.columns)
shopping_carts has shape: (5, 2)
shopping_carts has dimension: 2
shopping_carts has a total of: 10 elements
The data in shopping_carts is:
[[ 500. 245.]
[ 40. nan]
[ 110. nan]
[ 45. 25.]
[ nan 55.]]
The row index in shopping_carts is: Index(['bike', 'book', 'glasses', 'pants', 'watch'], dtype='object')
The column index in shopping_carts is: Index(['Alice', 'Bob'], dtype='object')
在 shopping_carts DataFrame 時,我們將整個字典傳遞給了 pd.DataFrame() 函數(shù)。但是,有時候你可能只對一部分數(shù)據(jù)感興趣。在 Pandas 中,我們可以通過關(guān)鍵字 columns和 index 選擇要將哪些數(shù)據(jù)放入 DataFrame 中。我們來看一些示例:
# We Create a DataFrame that only has Bob's data
bob_shopping_cart = pd.DataFrame(items, columns=['Bob'])
# We display bob_shopping_cart
bob_shopping_cart
| Bob | |
|---|---|
| bike | 245 |
| pants | 25 |
| watch | 55 |
# We Create a DataFrame that only has selected items for both Alice and Bob
sel_shopping_cart = pd.DataFrame(items, index = ['pants', 'book'])
# We display sel_shopping_cart
sel_shopping_cart
| Alice | Bob | |
|---|---|---|
| pants | 45 | 25.0 |
| book | 40 | NaN |
# We Create a DataFrame that only has selected items for Alice
alice_sel_shopping_cart = pd.DataFrame(items, index = ['glasses', 'bike'], columns = ['Alice'])
# We display alice_sel_shopping_cart
alice_sel_shopping_cart
| Alice | |
|---|---|
| glasses | 110 |
| bike | 500 |
你還可以使用列表(數(shù)組)字典手動地創(chuàng)建 DataFrame。流程和之前一樣,首先創(chuàng)建一個字典,然后將該字典傳遞給 pd.DataFrame() 函數(shù)。但是在這種情況下,字典中的所有列表(數(shù)組)長度必須一樣。我們來看一個示例:
# We create a dictionary of lists (arrays)
data = {'Integers' : [1,2,3],
'Floats' : [4.5, 8.2, 9.6]}
# We create a DataFrame
df = pd.DataFrame(data)
# We display the DataFrame
df
| Floats | Integers | |
|---|---|---|
| 0 | 4.5 | 1 |
| 1 | 8.2 | 2 |
| 2 | 9.6 | 3 |
注意,因為我們創(chuàng)建的 data 字典沒有標簽索引,因此 Pandas 在創(chuàng)建 DataFrame 時自動使用數(shù)字行索引。但是,我們可以通過在 pd.DataFrame() 函數(shù)中使用關(guān)鍵字 index,為行索引添加標簽。我們來看一個示例:
# We create a dictionary of lists (arrays)
data = {'Integers' : [1,2,3],
'Floats' : [4.5, 8.2, 9.6]}
# We create a DataFrame and provide the row index
df = pd.DataFrame(data, index = ['label 1', 'label 2', 'label 3'])
# We display the DataFrame
df
| Floats | Integers | |
|---|---|---|
| label 1 | 4.5 | 1 |
| label 2 | 8.2 | 2 |
| label 3 | 9.6 | 3 |
手動創(chuàng)建 Pandas DataFrame 的最后一種方式是使用 Python 字典列表。流程和之前一樣,我們先創(chuàng)建字典,然后將該字典傳遞給 pd.DataFrame() 函數(shù)。
# We create a list of Python dictionaries
items2 = [{'bikes': 20, 'pants': 30, 'watches': 35},
{'watches': 10, 'glasses': 50, 'bikes': 15, 'pants':5}]
# We create a DataFrame
store_items = pd.DataFrame(items2)
# We display the DataFrame
store_items
| bikes | glasses | pants | watches | |
|---|---|---|---|---|
| 0 | 20 | NaN | 30 | 35 |
| 1 | 15 | 50.0 | 5 | 10 |
同樣注意,因為我們創(chuàng)建的 items2 字典沒有標簽索引,因此 Pandas 在創(chuàng)建 DataFrame 時自動使用數(shù)字行索引。和之前一樣,我們可以通過在 pd.DataFrame() 函數(shù)中使用關(guān)鍵字 index,為行索引添加標簽。假設(shè)我們將使用該 DataFrame 存儲某個商店的商品庫存數(shù)量。我們將行索引的標簽設(shè)為 store 1 和 store 2。
# We create a list of Python dictionaries
items2 = [{'bikes': 20, 'pants': 30, 'watches': 35},
{'watches': 10, 'glasses': 50, 'bikes': 15, 'pants':5}]
# We create a DataFrame and provide the row index
store_items = pd.DataFrame(items2, index = ['store 1', 'store 2'])
# We display the DataFrame
store_items
| bikes | glasses | pants | watches | |
|---|---|---|---|---|
| store 1 | 20 | NaN | 30 | 35 |
| store 2 | 15 | 50.0 | 5 | 10 |