作者:李明江 張良均 周東平 張尚佳
來源:大數據DT(ID:hzdashuju)
pandas提供了眾多類,可滿足不同的使用需求,其中常用的類如下所示。Series:基本數據結構,一維標籤數組,能夠保存任何數據類型DataFrame:基本數據結構,一般為二維數組,是一組有序的列Index:索引對象,負責管理軸標籤和其他元數據(比如軸名稱)groupby:分組對象,通過傳入需要分組的參數實現對數據分組Timestamp:時間戳對象,表示時間軸上的一個時刻Timedelta:時間差對象,用來計算兩個時間點的差值在這6個類中,Series、DataFrame和Index是使用頻率最高的類。Series由一組數據以及一組與之對應的數據標籤(即索引)組成。Series對象可以視作一個NumPy的ndarray,因此許多NumPy庫函數可以作用於Series。創建Series對象的函數是Series,它的主要參數是data和index,其基本語法格式如下。class pandas.Series(data=None, index=None, dtype=None, name=None, copy=False, fastpath=False)
import pandas as pd
import numpy as np
print('通過ndarray創建的Series為:\n',
pd.Series(np.arange(5), index = ['a', 'b', 'c', 'd', 'e'], name = 'ndarray'))
輸出:
通過ndarray創建的Series為:
a 0
b 1
c 2
d 3
e 4
Name: ndarray, dtype: int32
dit = {'a': 0, 'b': 1, 'c': 2, 'd': 3, 'e': 4}
print('通過dict創建的Series為:\n', pd.Series(dit))
通過dict創建的Series為:
a 0
b 1
c 2
d 3
e 4
dtype: int64
list1 = [0, 1, 2, 3, 4]
print('通過list創建的Series為:\n', pd.Series(list1, index = ['a', 'b', 'c', 'd', 'e'], name = 'list'))
通過list創建的Series為:
a 0
b 1
c 2
d 3
e 4
Name: list, dtype: int64
series = pd.Series(list1, index = ['a', 'b', 'c', 'd', 'e'], name = 'list')
print('數組形式返回Series為:', series.values)
#輸出:數組形式返回Series為: [0 1 2 3 4]
print('Series的Index為:', series.index)
#輸出:Series的Index為:Index(['a', 'b', 'c', 'd', 'e'], dtype='object')
print('Series的形狀為:', series.shape)
#輸出:Series的形狀為: (5,)
print('Series的維度為:', series.ndim)
#輸出:Series的維度為:1
print('Series位於第1位置的數據為:', series[0])
print('Series中Index為a的數據為:', series['a'])
bool = (series < 4)
print('bool類型的Series為:\n', bool)
輸出:
bool類型的Series為:
a True
b True
c True
d True
e False
Name: list, dtype: bool
print('通過bool數據訪問Series結果為:\n', series[bool])
通過bool數據訪問Series結果為:
a 0
b 1
c 2
d 3
Name: list, dtype: int64
# 更新元素
series['a'] = 3
print('更新後的Series為:\n', series)
更新後的Series為:
a 3
b 1
c 2
d 3
e 4
Name: list, dtype: int64
series1 = pd.Series([4, 5], index = ['f', 'g'])
# 追加Series
print('在series插入series1後為:\n', series.append(series1))
在series插入series1後為:
a 3
b 1
c 2
d 3
e 4
f 4
g 5
dtype: int64
# 新增單個數據
series1['h'] = 7
print('在series1插入單個數據後為:\n', series1)
在series1插入單個數據後為:
f 4
g 5
h 7
dtype: int64
# 刪除數據
series.drop('e', inplace = True)
print('刪除索引e對應數據後的series為:\n', series)
輸出:
刪除索引e對應數據後的series為:
a 3
b 1
c 2
d 3
Name: list, dtype: int64
class pandas.DataFrame(data=None, index=None, columns=None, dtype=None, copy=False)
dict1 = {'col1': [0, 1, 2, 3, 4], 'col2': [5, 6, 7, 8, 9]}
print('通過dict創建的DataFrame為:\n', pd.DataFrame(dict1, index = ['a', 'b', 'c', 'd', 'e']))
通過dict創建的DataFrame為:
col1 col2
a 0 5
b 1 6
c 2 7
d 3 8
e 4 9
list2 = [[0, 5], [1, 6], [2, 7], [3, 8], [4, 9]]
print('通過list創建的DataFrame為:\n',
pd.DataFrame(list2, index = ['a', 'b', 'c', 'd', 'e'], columns = ['col1', 'col2']))
通過list創建的DataFrame為:
col1 col2
a 0 5
b 1 6
c 2 7
d 3 8
e 4 9
df = pd.DataFrame({'col1': [0, 1, 2, 3, 4], 'col2': [5, 6, 7, 8, 9]},
index = ['a', 'b', 'c', 'd', 'e'])
print('DataFrame的Index為:', df.index)
#輸出:DataFrame的Index為:Index(['a', 'b', 'c', 'd', 'e'], dtype='object')
print('DataFrame的列標籤為:', df.columns)
#輸出:DataFrame的列標籤為:Index(['col1', 'col2'], dtype='object')
print('DataFrame的軸標籤為:', df.axes)
#輸出:DataFrame的軸標籤為: [Index(['a', 'b', 'c', 'd', 'e'], dtype='object'), Index(['col1', 'col2'], dtype='object')]
print('DataFrame的維度為:', df.ndim)
#輸出:DataFrame的維度為:2
print('DataFrame的形狀為:', df.shape)
#輸出:DataFrame的形狀為: (5, 2)
print('默認返回前5行數據為:\n', df.head())
輸出:
默認返回前5行數據為:
col1 col2
a 0 5
b 1 6
c 2 7
d 3 8
e 4 9
print('返回後3行數據為:\n', df.tail(3))
輸出:
返回後3行數據為:
col1 col2
c 2 7
d 3 8
e 4 9
# 更新列
df['col1'] = [10, 11, 12, 13, 14]
print('更新列後的DataFrame為:\n', df)
更新列後的DataFrame為:
col1 col2
a 10 5
b 11 6
c 12 7
d 13 8
e 14 9
# 插入列
df['col3'] = [15, 16, 17, 18, 19]
print('插入列後的DataFrame為:\n', df)
插入列後的DataFrame為:
col1 col2 col3
a 10 5 15
b 11 6 16
c 12 7 17
d 13 8 18
e 14 9 19
DataFrame.drop(labels, axis=0, level=None, inplace=False, errors='raise')
labels:接收string或array。表示刪除的行或列的標籤。無默認值axis:接收0或1。表示執行操作的軸向,其中0表示刪除行,1表示刪除列。默認為0levels:接收int或者索引名。表示索引級別。默認為Noneinplace:接收bool。表示操作是否對原數據生效。默認為False使用drop方法刪除數據,如代碼清單6-17所示。# 刪除列
df.drop(['col3'], axis = 1, inplace = True)
print('刪除col3列後的DataFrame為:\n', df)
刪除col3列後的DataFrame為:
col1 col2
a 10 5
b 11 6
c 12 7
d 13 8
e 14 9
# 刪除行
df.drop('a', axis = 0, inplace = True)
print('刪除a行後的DataFrame為:\n', df)
刪除a行後的DataFrame為:
col1 col2
b 11 6
c 12 7
d 13 8
e 14 9
print('series的Index為 :\n', series.index)
series的Index為 :
Index(['a', 'b', 'c', 'd'], dtype='object')
print('series中Index各元素是否大於前一個:', series.index.is_monotonic)
#輸出:series中Index各元素是否大於前一個:True
print('series中Index各元素是否唯一:', series.index.is_unique)
#輸出:series中Index各元素是否唯一:True
index1 = series.index
index2 = series1.index
print('index1連接index2後結果為:\n', index1.append(index2))
#輸出:index1連接index2後結果為:
# Index(['a', 'b', 'c', 'd', 'f', 'g', 'h'], dtype='object')