pandas庫簡介和數據結構

pandas簡介

pandas是一個強大的Python數據分析的工具包。是基於Numpy來構件的。python

pandas提供快速、靈活和富有表現力的數據結構。數組

主要功能:數據結構

  • 具有對其功能的數據結構DataFrame、Seriesapp

  • 集成時間序列功能dom

  • 提供豐富的數學運算和操做函數

  • 靈活處理缺失數據工具

安裝spa

pip install pandas

pandas數據結構-系列Series

Series是一種相似於一位數組的對象,由一組數據和一組與之相關的數據標籤(索引)組成。code

  • values:一組數據(ndarray類型)對象

  • index:相關的數據索引標籤

pandas系列能夠使用以下構造函數建立

pandas.Series( data, index, dtype, copy)

參數以下

編號 參數 描述
1 data 數據採起各類形式,如:ndarraylistconstants
2 index 索引值必須是惟一的和散列的,與數據的長度相同。 默認np.arange(n)若是沒有索引被傳遞。
3 dtype dtype用於數據類型。若是沒有,將推斷數據類型
4 copy 複製數據,默認爲false

series建立

1.經過列表或numpy數組建立,默認索引爲0到N-1的整數型索引(隱式索引)

# 使用列表建立series
Series(data=[1,2,3,4])
​
# 經過設置index參數指定索引
s = Series(data=[1,2,3,4],index=["a","b","c","d"])
​
# 經過numpy建立
Series(data=np.random.randint(0,100,size=(3,)))

2.經過字典建立

# 經過字典建立series
s = Series(data={'a':1, 'b':2})

3.從標量建立一個系列

import pandas as pd
import numpy as np
s = pd.Series(5, index=[0, 1, 2, 3])

Series特性

Series支持數組的特性

  • 從ndarray建立Series:Series(arr)

  • 與標量運算:sr*2

  • 兩個Series運算:sr1+sr2

  • 索引:sr[0], sr[[1,2,4]]

  • 切片:sr[0:2](切片依然是視圖形式)

  • 通用函數:np.abs(sr)

  • 布爾值過濾:sr[sr>0]

s1 = Series(data=[1,2,3,4],index=["a","b","c","d"])
s2 = Series(data=[1,2,3,4],index=["a","b","e","d"])
s3 = s1+s2

統計函數

  • mean():求平均數

  • sum():求和

  • cumsum():累加

s = pd.Series({"a":1,"b":2,"c":3,"d":5,"e":7})
s.cumsum()

Series支持字典的特性(標籤)

  • 從字典建立Series:Series(dic),

  • in運算:’a’ in sr、for x in sr

  • 鍵索引:sr['a'], sr[['a', 'b', 'd']]

  • 鍵切片:sr['a':'c']

  • 其餘函數:get('a', default=0)等

# 點索引取值
s = pd.Series(0,index=["a","b","c","d","e"])
s.a
# 0
​
s1 = pd.Series({'a':1,'b':2})
s1.a  # 1
s1[0]  # 1
​
s1*2
a 2
b 4

Series索引

1.具備位置的系列訪問數據

系列中的數據能夠使用相似於訪問ndarray中的數據來訪問

s = pd.Series([1,2,3,4,5],index = ['a','b','c','d','e'])
# 檢索第一個元素
print s[0]
# 檢索系列中的前三個元素
print s[:3]
# 檢索最後三個元素
print s[-3:]

2.使用標籤檢索數據(索引)

一個系列就像一個固定大小的字典,能夠經過索引標籤獲取和設置值。

import pandas as pd
s = pd.Series([1,2,3,4,5],index = ['a','b','c','d','e'])
​
# 使用索引標籤值檢索單個元素
print(s["a"])
​
# 使用索引標籤值列表檢索多個元素
print(s[['a','c','d']])
​
# 若是不包含標籤,則會出現異常
print s['f']
# keyError:"f"

Series數據對齊

pandas在運算時,會按索引進行對齊而後計算。若是存在不一樣的索引,則結果的索引是兩個操做數索引的並集。

  • 在運算中自動對齊不一樣索引的數據

  • 若是索引不對應,則補NaN

s1 = Series(data=[1,2,3,4],index=["a","b","c","d"])
s2 = Series(data=[1,2,3,4],index=["a","b","e","d"])
s3 = s1+s2
# 輸出
a    2.0
b    4.0
c    NaN
d    8.0
e    NaN
dtype: float64

當索引沒有對應的值,可能會出現缺失數據顯示NaN(not a number)的狀況。

s3.isnull()  # 爲空檢測
s3.notnull()  # 非空檢測
s3[[True,True,False,True,False]]  # 若是將布爾值做爲Series的索引,則只會保留True對應的元素的值
s3[s3.notnull()]  # 直接能夠返回沒有缺失的數據
# 輸出:
a    2.0
b    4.0
d    8.0
dtype: float64

pandas數據結構-數據幀DataFrame

數據幀(DataFrame)是二維數據結構,即數據以行和列的表格方式排列。

數據幀(DataFrame)的功能特色:

  • 潛在的列是不一樣的類型

  • 大小可變

  • 標記軸(行和列)

  • 能夠對行和列執行算術運算

pandas中的DataFrame能夠使用如下構造函數建立

pandas.DataFrame( data, index, columns, dtype, copy)

參數以下:

編號 參數 描述
1 data 數據採起各類形式,如:ndarrayseriesmaplistsdictconstant和另外一個DataFrame
2 index 對於行標籤,要用於結果幀的索引是可選缺省值np.arrange(n),若是沒有傳遞索引值。
3 columns 對於列標籤,可選的默認語法是 - np.arange(n)。 這隻有在沒有索引傳遞的狀況下才是這樣。
4 dtype 每列的數據類型。
5 copy 若是默認值爲False,則此命令(或任何它)用於複製數據。

建立DataFrame

Pandas數據幀(DataFrame)能夠使用各類輸入建立,如 -

  • 列表

  • 字典

  • 系列

  • Numpy ndarrays

  • 另外一個數據幀(DataFrame)

# 建立一個空數據幀
import pandas as pd
df = pd.DataFrame()
​
# 從列表建立DataFrame
data = [1,2,3,4,5]
df = pd.DataFrame(data)

從ndarrays/Lists的字典來建立DataFrame

全部的ndarrays必須具備相同的長度。若是傳遞了索引(index),則索引的長度應等於數組的長度。

若是沒有傳遞索引,則默認狀況下,索引將爲range(n),其中n爲數組長度。

import pandas as pd
data = {'Name':['Tom', 'Jack', 'Steve', 'Ricky'],'Age':[28,34,29,42]}
df = pd.DataFrame(data)
​
# 使用數組建立一個索引的數據幀
data = {'Name':['Tom', 'Jack', 'Steve', 'Ricky'],'Age':[28,34,29,42]}
df = pd.DataFrame(data, index=['rank1','rank2','rank3','rank4'])

從系列的字典來建立DataFrame

字典的系列能夠傳遞以造成一個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)

DataFrame數據查詢

列的相關操做

列選擇

從數據幀(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)
df["one"]
​
輸出
a     1.0
b     2.0
c     3.0
d     NaN
Name: one, dtype: float64

列添加

經過向現有數據框添加一個新列

print ("Adding a new column by passing as Series:")
df['three']=pd.Series([10,20,30],index=['a','b','c'])
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

列刪除

列能夠刪除或彈出

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 ("Deleting the first column using DEL function:")
del df['one']

行的相關操做

行的標籤選擇

經過將行標籤傳遞給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

行的整數位置選擇

能夠經過將整數位置傳遞給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'])
df2 = pd.DataFrame([[5, 6], [7, 8]], columns = ['a','b'])
​
df = df.append(df2)
​
# Drop rows with label 0
df = df.drop(0)
​
print(df)

執行上面示例代碼,獲得如下結果 -

  a b
1 3 4
1 7 8
相關文章
相關標籤/搜索