pandas庫簡介和數據結構


pandas簡介

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

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

主要功能:

  • 具備對其功能的數據結構DataFrame、Series

  • 集成時間序列功能

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

  • 靈活處理缺失數據

安裝

pip install pandas

pandas數據結構-系列Series

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

  • 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

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM