數據幀(DataFrame)是二維數據結構,即數據以行和列的表格方式排列。python
數據幀(DataFrame)的功能特色:shell
結構體數組
假設要建立一個包含學生數據的數據幀。參考如下圖示 -數據結構
能夠將上圖表視爲SQL表或電子表格數據表示。app
pandas中的DataFrame
可使用如下構造函數建立 -函數
pandas.DataFrame( data, index, columns, dtype, copy)
參數 | 描述 |
---|---|
data |
數據採起各類形式,如:ndarray ,series ,map ,lists ,dict ,constant 和另外一個DataFrame 。 |
index |
對於行標籤,要用於結果幀的索引是可選缺省值np.arrange(n) ,若是沒有傳遞索引值。 |
columns |
對於列標籤,可選的默認語法是 - np.arange(n) 。 這隻有在沒有索引傳遞的狀況下才是這樣。 |
dtype |
每列的數據類型。 |
copy |
若是默認值爲False ,則此命令(或任何它)用於複製數據。 |
Pandas數據幀(DataFrame)可使用各類輸入建立,如 -spa
在本章的後續章節中,咱們將看到如何使用這些輸入建立數據幀(DataFrame)。code
建立基本數據幀是空數據幀。blog
import pandas as pd df = pd.DataFrame() print(df)
輸出結果:索引
Empty DataFrame Columns: [] Index: []
可使用單個列表或列表列表建立數據幀(DataFrame)。
實例-1
import pandas as pd data = [1,2,3,4,5] df = pd.DataFrame(data) print(df)
輸出結果:
0 0 1 1 2 2 3 3 4 4 5
實例-2
import pandas as pd data = [['Alex',10],['Bob',12],['Clarke',13]] df = pd.DataFrame(data,columns=['Name','Age']) print(df)
輸出結果:
Name Age 0 Alex 10 1 Bob 12 2 Clarke 13
實例-3
import pandas as pd data = [['Alex',10],['Bob',12],['Clarke',13]] df = pd.DataFrame(data,columns=['Name','Age'],dtype=float) print(df)
輸出結果:
Name Age 0 Alex 10.0 1 Bob 12.0 2 Clarke 13.0
注意 - 能夠觀察到,
dtype
參數將Age
列的類型更改成浮點。
全部的ndarrays
必須具備相同的長度。若是傳遞了索引(index
),則索引的長度應等於數組的長度。
若是沒有傳遞索引,則默認狀況下,索引將爲range(n)
,其中n
爲數組長度。
實例-1
import pandas as pd data = {'Name':['Tom', 'Jack', 'Steve', 'Ricky'],'Age':[28,34,29,42]} df = pd.DataFrame(data) print(df)
輸出結果:
Age Name 0 28 Tom 1 34 Jack 2 29 Steve 3 42 Ricky
注 - 觀察值
0
,1
,2
,3
。它們是分配給每一個使用函數range(n)
的默認索引。
示例-2
使用數組建立一個索引的數據幀(DataFrame)。
import pandas as pd data = {'Name':['Tom', 'Jack', 'Steve', 'Ricky'],'Age':[28,34,29,42]} df = pd.DataFrame(data, index=['rank1','rank2','rank3','rank4']) print(df)
輸出結果:
Age Name rank1 28 Tom rank2 34 Jack rank3 29 Steve rank4 42 Ricky
注意 -
index
參數爲每行分配一個索引。
字典列表可做爲輸入數據,用來建立數據幀(DataFrame),字典鍵默認爲列名。
實例-1
如下示例顯示如何經過傳遞字典列表來建立數據幀(DataFrame)。
import pandas as pd data = [{'a': 1, 'b': 2},{'a': 5, 'b': 10, 'c': 20}] df = pd.DataFrame(data) print(df)
輸出結果:
a b c 0 1 2 NaN 1 5 10 20.0
注意 - 觀察到,NaN(不是數字)被附加在缺失的區域。
示例-2
如下示例顯示如何經過傳遞字典列表和行索引來建立數據幀(DataFrame)。
import pandas as pd data = [{'a': 1, 'b': 2},{'a': 5, 'b': 10, 'c': 20}] df = pd.DataFrame(data, index=['first', 'second']) print(df)
輸出結果:
a b c first 1 2 NaN second 5 10 20.0
實例-3
如下示例顯示如何使用字典,行索引和列索引列表建立數據幀(DataFrame)。
import pandas as pd data = [{'a': 1, 'b': 2},{'a': 5, 'b': 10, 'c': 20}] #With two column indices, values same as dictionary keys df1 = pd.DataFrame(data, index=['first', 'second'], columns=['a', 'b']) #With two column indices with one index with other name df2 = pd.DataFrame(data, index=['first', 'second'], columns=['a', 'b1']) print(df1) print('\n') print(df2)
輸出結果:
a b first 1 2 second 5 10 a b1 first 1 NaN second 5 NaN
注意 - 觀察,
df2
使用字典鍵之外的列索引建立DataFrame
; 所以,附加了NaN到位置上。 而df1
是使用列索引建立的,與字典鍵相同,因此也附加了NaN。
字典的系列能夠傳遞以造成一個DataFrame。 所獲得的索引是全部系列索引的並集。
示例
import pandas as pd d = {'one' : pd.Series([1, 2, 3], index=['a', 'b', 'c']), 'two' : pd.Series([1, 2, 3, 4], index=['a', 'b', 'c', 'd'])} df = pd.DataFrame(d) print(df)
輸出結果:
one two a 1.0 1 b 2.0 2 c 3.0 3 d NaN 4
注意 - 對於第一個系列,觀察到沒有傳遞標籤
'd'
,但在結果中,對於d
標籤,附加了NaN。
經過列名,來選擇列
import pandas as pd d = {'one' : pd.Series([1, 2, 3], index=['a', 'b', 'c']), 'two' : pd.Series([1, 2, 3, 4], index=['a', 'b', 'c', 'd'])} df = pd.DataFrame(d) print(df ['one'])
輸出結果:
a 1.0 b 2.0 c 3.0 d NaN Name: one, dtype: float64
像字典賦值同樣直接添加。
import pandas as pd d = {'one' : pd.Series([1, 2, 3], index=['a', 'b', 'c']), 'two' : pd.Series([1, 2, 3, 4], index=['a', 'b', 'c', 'd'])} df = pd.DataFrame(d) # Adding a new column to an existing DataFrame object with column label by passing new series print ("Adding a new column by passing as Series:") df['three']=pd.Series([10,20,30],index=['a','b','c']) print(df) print('\n') print ("Adding a new column using the existing columns in DataFrame:") df['four']=df['one']+df['three'] print(df)
輸出結果:
Adding a new column by passing as Series: one two three a 1.0 1 10.0 b 2.0 2 20.0 c 3.0 3 30.0 d NaN 4 NaN Adding a new column using the existing columns in DataFrame: one two three four a 1.0 1 10.0 11.0 b 2.0 2 20.0 22.0 c 3.0 3 30.0 33.0 d NaN 4 NaN NaN
列能夠刪除或彈出;
import pandas as pd d = {'one' : pd.Series([1, 2, 3], index=['a', 'b', 'c']), 'two' : pd.Series([1, 2, 3, 4], index=['a', 'b', 'c', 'd']), 'three' : pd.Series([10,20,30], index=['a','b','c'])} df = pd.DataFrame(d) print ("Our dataframe is:") print(df) print('\n') # using del function print ("Deleting the first column using DEL function:") del df['one'] print(df) print('\n') # using pop function print ("Deleting column using POP function:") df.pop('two') print(df)
輸出結果 -
Our dataframe is: one three two a 1.0 10.0 1 b 2.0 20.0 2 c 3.0 30.0 3 d NaN NaN 4 Deleting the first column using DEL function: three two a 10.0 1 b 20.0 2 c 30.0 3 d NaN 4 Deleting column using POP function: three a 10.0 b 20.0 c 30.0 d NaN
標籤選擇
能夠經過將行標籤傳遞給loc()
函數來選擇行。參考如下示例代碼 -
import pandas as pd d = {'one' : pd.Series([1, 2, 3], index=['a', 'b', 'c']), 'two' : pd.Series([1, 2, 3, 4], index=['a', 'b', 'c', 'd'])} df = pd.DataFrame(d) print(df.loc['b'])
輸出結果:
one 2.0 two 2.0 Name: b, dtype: float64
結果是一系列標籤做爲DataFrame
的列名稱。 並且,系列的名稱是檢索的標籤。
按整數位置選擇
能夠經過將整數位置傳遞給iloc()
函數來選擇行。參考如下示例代碼 -
import pandas as pd d = {'one' : pd.Series([1, 2, 3], index=['a', 'b', 'c']), 'two' : pd.Series([1, 2, 3, 4], index=['a', 'b', 'c', 'd'])} df = pd.DataFrame(d) print(df.iloc[2])
輸出結果:
one 3.0 two 3.0 Name: c, dtype: float64
可使用:
運算符選擇多行。參考如下示例代碼 -
import pandas as pd d = {'one' : pd.Series([1, 2, 3], index=['a', 'b', 'c']), 'two' : pd.Series([1, 2, 3, 4], index=['a', 'b', 'c', 'd'])} df = pd.DataFrame(d) print(df[2:4])
輸出結果:
one two c 3.0 3 d NaN 4
附加行
使用append()
函數將新行添加到DataFrame。 此功能將附加行結束。
import pandas as pd df = pd.DataFrame([[1, 2], [3, 4]], columns = ['a','b']) df2 = pd.DataFrame([[5, 6], [7, 8]], columns = ['a','b']) df = df.append(df2) print(df)
輸出結果:
a b 0 1 2 1 3 4 0 5 6 1 7 8
刪除行
使用索引標籤從DataFrame中刪除或刪除行。 若是標籤重複,則會刪除多行。
import pandas as pd df = pd.DataFrame([[1, 2], [3, 4]], columns = ['a','b']) print(df) print('\n') df2 = pd.DataFrame([[5, 6], [7, 8]], columns = ['a','b']) print(df2) print('\n') df = df.append(df2) print(df) print('\n') # Drop rows with label 0 df = df.drop(0) print(df)
輸出結果:
a b
0 1 2
1 3 4
a b
0 5 6
1 7 8
a b
0 1 2
1 3 4
0 5 6
1 7 8
a b
1 3 4
1 7 8
在上面的例子中,一共有兩行被刪除,由於這兩行包含相同的標籤0
。