柚子快報邀請碼778899分享:認(rèn)識pandas
柚子快報邀請碼778899分享:認(rèn)識pandas
1 認(rèn)識pandas
Pandas 是一個開源的第三方 Python 庫,從 Numpy 和 Matplotlib 的基礎(chǔ)上構(gòu)建而來,享有數(shù)據(jù)分析“三劍客之一”的盛名(NumPy、Matplotlib、Pandas)。Pandas 已經(jīng)成為 Python 數(shù)據(jù)分析的必備高級工具,它的目標(biāo)是成為強(qiáng)大、靈活、可以支持任何編程語言的數(shù)據(jù)分析工具。
1.1 pandas主要特點(diǎn)
Pandas 主要包括以下幾個特點(diǎn):
它提供了一個簡單、高效、帶有默認(rèn)標(biāo)簽(也可以自定義標(biāo)簽)的 DataFrame 對象。 能夠快速得從不同格式的文件中加載數(shù)據(jù)(比如 Excel、CSV 、SQL文件),然后將其轉(zhuǎn)換為可處理的對象; 能夠按數(shù)據(jù)的行、列標(biāo)簽進(jìn)行分組,并對分組后的對象執(zhí)行聚合和轉(zhuǎn)換操作; 能夠很方便地實(shí)現(xiàn)數(shù)據(jù)歸一化操作和缺失值處理; 能夠很方便地對 DataFrame 的數(shù)據(jù)列進(jìn)行增加、修改或者刪除的操作; 能夠處理不同格式的數(shù)據(jù)集,比如矩陣數(shù)據(jù)、異構(gòu)數(shù)據(jù)表、時間序列等; 提供了多種處理數(shù)據(jù)集的方式,比如構(gòu)建子集、切片、過濾、分組以及重新排序等。
1.2 pandas的優(yōu)勢
與其它語言的數(shù)據(jù)分析包相比,Pandas 具有以下優(yōu)勢
Pandas 的 DataFrame 和 Series 構(gòu)建了適用于數(shù)據(jù)分析的存儲結(jié)構(gòu); Pandas 簡潔的 API 能夠讓你專注于代碼的核心層面; Pandas 實(shí)現(xiàn)了與其他庫的集成,比如 Scipy、scikit-learn 和 Matplotlib;
1.3 下載安裝
pip install pandas
2 pandas內(nèi)置數(shù)據(jù)結(jié)構(gòu)
Series 是帶標(biāo)簽的一維數(shù)組,這里的標(biāo)簽可以理解為索引,但這個索引并不局限于整數(shù),它也可以是字符類型,比如 a、b、c 等; DataFrame 是一種表格型數(shù)據(jù)結(jié)構(gòu),它既有行標(biāo)簽,又有列標(biāo)簽。
數(shù)據(jù)結(jié)構(gòu)維度說明Series1該結(jié)構(gòu)能夠存儲各種數(shù)據(jù)類型,比如字符數(shù)、整數(shù)、浮點(diǎn)數(shù)、Python 對象等,Series 用 name 和 index 屬性來描述 數(shù)據(jù)值。Series 是一維數(shù)據(jù)結(jié)構(gòu),因此其維數(shù)不可以改變。DataFrame2DataFrame 是一種二維表格型數(shù)據(jù)的結(jié)構(gòu),既有行索引,也有列索引。行索引是 index,列索引是 columns。 在創(chuàng)建該結(jié)構(gòu)時,可以指定相應(yīng)的索引值。
2.1 Pandas Series
2.1.1 創(chuàng)建series對象
Pandas 使用 Series() 函數(shù)來創(chuàng)建 Series 對象,通過這個對象可以調(diào)用相應(yīng)的方法和屬性,從而達(dá)到處理數(shù)據(jù)的目的
import pandas as pd
seriec_obj = pd.Series(data, index, dtype, copy)
?
# data 輸入的數(shù)據(jù),可以是列表、常量、ndarray 數(shù)組等。
# index 索引值必須是惟一的,如果沒有傳遞索引,則默認(rèn)為 np.arrange(n)。
# dtype dtype表示數(shù)據(jù)類型,如果沒有提供,則會自動判斷得出。
# copy 表示對 data 進(jìn)行拷貝,默認(rèn)為 False。
ndarray創(chuàng)建Series對象
arr_one = np.array(['a', 'b', 'c', 'd'])
arr_obj = pd.Series(arr_one, index=('a', 'b', 'c', 'd'))
arr_obj_two = pd.Series(arr_one, index=(1, 2, 3, 4))
print(arr_obj)
print("arr_obj_two為:\n", arr_obj_two)
代碼的運(yùn)行結(jié)果為:
a a
b b
c c
d d
dtype: object
arr_obj_two為:
1 a
2 b
3 c
4 d
dtype: object
ndarray 是 NumPy 中的數(shù)組類型,當(dāng) data 是 ndarry 時,傳遞的索引必須具有與數(shù)組相同的長度。假如沒有給 index 參數(shù)傳參,在默認(rèn)情況下,索引值將使用是 range(n) 生成,其中 n 代表數(shù)組長度
上述示例中沒有傳遞任何索引,所以索引默認(rèn)從 0 開始分配 ,其索引范圍為 0 到len(data)-1,即 0 到 3。這種設(shè)置方式被稱為“隱式索引”。
“顯式索引”的方法定義索引標(biāo)簽
arr_str = np.array(['張三', '李四', '王五', '趙六'])
# 自定義索引標(biāo)簽(即顯示索引)
ser_obj = pd.Series(arr_str, index=[1, 2, 3, 4])
print(ser_obj)
代碼的運(yùn)行結(jié)果為:
1 張三
2 李四
3 王五
4 趙六
dtype: object
dict創(chuàng)建Series對象
data = {'a': 0., 'b': 1., 'c': 2.}
ser_data = pd.Series(data)
print(ser_data)
代碼的運(yùn)行結(jié)果為:
a 0.0
b 1.0
c 2.0
dtype: float64
您可以把 dict 作為輸入數(shù)據(jù)。如果沒有傳入索引時會按照字典的鍵來構(gòu)造索引;反之,當(dāng)傳遞了索引時需要將索引標(biāo)簽與字典中的值一一對應(yīng)
data = {'a': 0., 'b': 1., 'c': 2.}
ser_data = pd.Series(data, index=['b', 'c', 'd', 'a'])
print(ser_data)
代碼的運(yùn)行結(jié)果為:
b 1.0
c 2.0
d NaN
a 0.0
dtype: float64
當(dāng)傳遞的索引值無法找到與其對應(yīng)的值時,使用 NaN(非數(shù)字)填充。
標(biāo)量創(chuàng)建Series對象
ser_data = pd.Series(5, index=[0, 1, 2, 3])
print(ser_data)
代碼的運(yùn)行結(jié)果為:
0 5
1 5
2 5
3 5
dtype: int64
2.1.2 訪問Series數(shù)據(jù)
訪問 Series 序列中元素,分為兩種方式,一種是位置索引訪問;另一種是索引標(biāo)簽訪問。
位置索引訪問
ser_data = pd.Series([1, 2, 3, 4, 5], index=['a', 'b', 'c', 'd', 'e'])
print(ser_data)
print(ser_data[0]) # 位置下標(biāo)
print(ser_data['a']) # 標(biāo)簽下標(biāo)
print(ser_data['b'])
代碼的運(yùn)行結(jié)果為:
a 1
b 2
c 3
d 4
e 5
dtype: int64
1
1
2
這種訪問方式與 ndarray 和 list 相同,使用元素自身的下標(biāo)進(jìn)行訪問。我們知道數(shù)組的索引計數(shù)從 0 開始,這表示第一個元素存儲在第 0 個索引位置上,以此類推,就可以獲得 Series 序列中的每個元素
通過切片的方式訪問 Series 序列中的數(shù)據(jù)
ser_data = pd.Series([1, 2, 3, 4, 5], index=['a', 'b', 'c', 'd', 'e'])
print(ser_data[:3])
print(ser_data[:7])
print(ser_data[1:3])
代碼的運(yùn)行結(jié)果為:
a 1
b 2
c 3
dtype: int64
a 1
b 2
c 3
d 4
e 5
dtype: int64
b 2
c 3
dtype: int64
索引標(biāo)簽訪問
Series 類似于固定大小的 dict,把 index 中的索引標(biāo)簽當(dāng)做 key,而把 Series 序列中的元素值當(dāng)做 value,然后通過 index 索引標(biāo)簽來訪問或者修改元素值。
ser_data = pd.Series([6, 7, 8, 9, 10], index=['a', 'b', 'c', 'd', 'e'])
print(ser_data[['a', 'c', 'd']])
代碼的運(yùn)行結(jié)果:
a 6
c 8
d 9
dtype: int64
2.1.3 Series常用屬性
名稱屬性axes以列表的形式返回所有行索引標(biāo)簽。dtype返回對象的數(shù)據(jù)類型。empty返回一個空的 Series 對象。ndim返回輸入數(shù)據(jù)的維數(shù)。size返回輸入數(shù)據(jù)的元素數(shù)量。values以 ndarray 的形式返回 Series 對象。index返回一個RangeIndex對象,用來描述索引的取值范圍。
ser_data = pd.Series(np.array([10, 20, 30, 40, 50]))
print("ser_data:\n", ser_data)
print("axes:\n", ser_data.axes)
print("dtype為:\n", ser_data.dtype)
print("empty:\n", ser_data.empty)
print("ndim:\n", ser_data.ndim)
print("size:\n", ser_data.size)
print("values:\n", ser_data.values)
print("index:\n", ser_data.index)
代碼的運(yùn)行結(jié)果為:
ser_data:
0 10
1 20
2 30
3 40
4 50
dtype: int32
axes:
[RangeIndex(start=0, stop=5, step=1)]
dtype為:
int32
empty:
False
ndim:
1
size:
5
values:
[10 20 30 40 50]
index:
RangeIndex(start=0, stop=5, step=1)
2.1.4 Series常用方法
2.1.4.1 head()&tail()
如果想要查看 Series 的某一部分?jǐn)?shù)據(jù),可以使用 head() 或者 tail() 方法
ser_data = pd.Series(np.random.randn(5))
print(ser_data)
# 返回前三行數(shù)據(jù)
print(ser_data.head(3))
代碼的運(yùn)行結(jié)果為:
0 1.863595
1 -1.478136
2 -0.632712
3 -0.046976
4 1.435217
dtype: float64
0 1.863595
1 -1.478136
2 -0.632712
dtype: float64
head() 返回前 n 行數(shù)據(jù),默認(rèn)顯示前 5 行數(shù)據(jù)
ser_data = pd.Series(np.array([1, 2, 3, 4, 5, 6, 7]))
print(ser_data.tail)
# 返回后三行數(shù)據(jù)
print(ser_data.tail(3))
代碼的運(yùn)行結(jié)果:
1 2
2 3
3 4
4 5
5 6
6 7
dtype: int32>
4 5
5 6
6 7
dtype: int32
tail() 返回的是后 n 行數(shù)據(jù),默認(rèn)為后 5 行
2.1.4.2 isnull()&nonull()
isnull() 和 nonull() 用于檢測 Series 中的缺失值。所謂缺失值,顧名思義就是值不存在、丟失、缺少。 在實(shí)際的數(shù)據(jù)分析任物中,數(shù)據(jù)的收集往往要經(jīng)歷一個繁瑣的過程。在這個過程中難免會因?yàn)橐恍┎豢煽沽Γ蛘呷藶橐蛩貙?dǎo)致數(shù)據(jù)丟失的現(xiàn)象。這時,我們可以使用相應(yīng)的方法對缺失值進(jìn)行處理,比如數(shù)據(jù)補(bǔ)齊等方法。
# None代表缺失數(shù)據(jù)
ser_data = pd.Series([1, 2, 5, None])
print(pd.isnull(ser_data)) # 是空值返回True
代碼的運(yùn)行結(jié)果為:
0 False
1 False
2 False
3 True
dtype: bool
isnull():如果為值不存在或者缺失,則返回 True。
# None代表缺失數(shù)據(jù)
ser_data = pd.Series([1, 2, 5, None])
print(pd.notnull(ser_data)) # 空值返回False
代碼的運(yùn)行結(jié)果為:
0 True
1 True
2 True
3 False
dtype: bool
notnull():如果值不存在或者缺失,則返回 False。
2.2 Pandas DataFrame
DataFrame 是 Pandas 的重要數(shù)據(jù)結(jié)構(gòu)之一,也是在使用 Pandas 進(jìn)行數(shù)據(jù)分析過程中最常用的結(jié)構(gòu)之一,可以這么說,掌握了 DataFrame 的用法,你就擁有了學(xué)習(xí)數(shù)據(jù)分析的基本能力。 DataFrame 一個表格型的數(shù)據(jù)結(jié)構(gòu),既有行標(biāo)簽(index),又有列標(biāo)簽(columns),它也被稱異構(gòu)數(shù)據(jù)表,所謂異構(gòu),指的是表格中每列的數(shù)據(jù)類型可以不同,比如可以是字符串、整型或者浮點(diǎn)型等。
DataFrame 結(jié)構(gòu)類似于 Execl 的表格型,表格中列標(biāo)簽的含義如下所示:
indexstudent_idstudent_namestudent_num01001James82.611002Pitter76.521003Jack92.331004Alice88.5
同 Series 一樣,DataFrame 自帶行標(biāo)簽索引,默認(rèn)為“隱式索引”即從 0 開始依次遞增,行標(biāo)簽與 DataFrame 中的數(shù)據(jù)項(xiàng)一一對應(yīng)。上述表格的行標(biāo)簽從 0 到 3,共記錄了 4 條數(shù)據(jù)(圖中將行標(biāo)簽省略)。當(dāng)然你也可以用“顯式索引”的方式來設(shè)置行標(biāo)簽。
下面對 DataFrame 數(shù)據(jù)結(jié)構(gòu)的特點(diǎn)做簡單地總結(jié),如下所示:
DataFrame 每一列的標(biāo)簽值允許使用不同的數(shù)據(jù)類型; DataFrame 是表格型的數(shù)據(jù)結(jié)構(gòu),具有行和列; DataFrame 中的每個數(shù)據(jù)值都可以被修改。 DataFrame 結(jié)構(gòu)的行數(shù)、列數(shù)允許增加或者刪除; DataFrame 有兩個方向的標(biāo)簽軸,分別是行標(biāo)簽和列標(biāo)簽; DataFrame 可以對行和列執(zhí)行算術(shù)運(yùn)算。
2.2.1 創(chuàng)建DataFrame對象
使用下列方式創(chuàng)建一個空的 DataFrame,這是 DataFrame 最基本的創(chuàng)建方法
df = pd.DataFrame()
print(df)
代碼的運(yùn)行結(jié)果為:
Empty DataFrame
Columns: []
Index: []
列表創(chuàng)建DataFame對象
data = [1, 2, 3, 4, 5]
df = pd.DataFrame(data)
print(df)
代碼的運(yùn)行結(jié)果為:
0
0 1
1 2
2 3
3 4
4 5
使用嵌套列表創(chuàng)建 DataFrame 對象
data = [['Alex', 10], ['Bob', 12], ['Clarke', 13]]
df = pd.DataFrame(data, columns=['Name', 'Age'])
print(df)
代碼的運(yùn)行結(jié)果為:
Name Age
0 Alex 10
1 Bob 12
2 Clarke 13
字典嵌套列表創(chuàng)建
data = {'Name': ['Tom', 'Jack', 'Steve', 'Ricky'], 'Age': [28, 34, 29, 42]}
df = pd.DataFrame(data)
print(df)
代碼的運(yùn)行結(jié)果為:
Name Age
0 Tom 28
1 Jack 34
2 Steve 29
3 Ricky 42
data 字典中,鍵對應(yīng)的值的元素長度必須相同(也就是列表長度相同)。如果傳遞了索引,那么索引的長度應(yīng)該等于數(shù)組的長度;如果沒有傳遞索引,那么默認(rèn)情況下,索引將是 range(n),其中 n 代表數(shù)組長度。
添加自定義的行標(biāo)簽
data = {'Name': ['Tom', 'Jack', 'Steve', 'Ricky'], 'Age': [28, 34, 29, 42]}
df = pd.DataFrame(data, index=['rank1', 'rank2', 'rank3', 'rank4'])
print(df)
代碼的運(yùn)行結(jié)果為:
Name Age
rank1 Tom 28
rank2 Jack 34
rank3 Steve 29
rank4 Ricky 42
列表嵌套字典創(chuàng)建DataFrame對象
data = [{'num': 1, 'result': 2}, {'num': 5, 'result': 10, 'number': 20}]
df = pd.DataFrame(data, index=['first', 'second'])
print(df)
代碼的運(yùn)行結(jié)果為:
num result number
first 1 2 NaN
second 5 10 20.0
如果其中某個元素值缺失,也就是字典的 key 無法找到對應(yīng)的 value,將使用 NaN 代替。
使用字典嵌套列表以及行、列索引表創(chuàng)建一個 DataFrame 對象。
data = [{'a': 1, 'b': 2}, {'a': 5, 'b': 10, 'c': 20}]
df1 = pd.DataFrame(data, index=['first', 'second'], columns=['a', 'b'])
df2 = pd.DataFrame(data, index=['first', 'second'], columns=['a', 'b1'])
df3 = pd.DataFrame(data, index=['first', 'second'], columns=['a', 'c'])
print("df1為:\n", df1)
print("df2為:\n", df2)
print("df3為:\n",df3)
代碼的運(yùn)行結(jié)果為:
df1為:
a b
first 1 2
second 5 10
df2為:
a b1
first 1 NaN
second 5 NaN
df3為:
a c
first 1 NaN
second 5 20.0
Series創(chuàng)建DataFrame對象 傳遞一個字典形式的 Series,從而創(chuàng)建一個 DataFrame 對象,其輸出結(jié)果的行索引是所有 index 的合集
dict_data = {
'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(dict_data)
print(df)
代碼的運(yùn)行結(jié)果為:
one two
a 1.0 1
b 2.0 2
c 3.0 3
d NaN 4
2.2.2 列索引操作DataFrame
DataFrame 可以使用列索(columns index)引來完成數(shù)據(jù)的選取、添加和刪除操作。
列索引選取數(shù)據(jù)列
dict_data = {
'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(dict_data)
print(df['one'])
代碼的運(yùn)行結(jié)果為:
a 1.0
b 2.0
c 3.0
d NaN
Name: one, dtype: float64
列索引添加數(shù)據(jù)列
dict_data = {
'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(dict_data)
# 使用df['列']=值,插入新的數(shù)據(jù)列
df['three'] = pd.Series([10, 20, 30], index=['a', 'b', 'c'])
print(df)
# 將已經(jīng)存在的數(shù)據(jù)列做相加運(yùn)算
df['four'] = df['one'] + df['three']
print(df)
代碼的運(yùn)行結(jié)果為:
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
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
除了使用df[]=value的方式外,您還可以使用 insert() 方法插入新的列
info = [['Jack', 18], ['Helen', 19], ['John', 17]]
df = pd.DataFrame(info, columns=['name', 'age'])
print(df)
# 注意是column參數(shù)
# 數(shù)值1代表插入到columns列表的索引位置
df.insert(1, column='score', value=[91, 90, 75])
print(df)
代碼的運(yùn)行結(jié)果為:
name age
0 Jack 18
1 Helen 19
2 John 17
name score age
0 Jack 91 18
1 Helen 90 19
2 John 75 17
這里需要注意的是使用insert函數(shù)的時候,傳入的value值,傳入的數(shù)據(jù)一定要與原數(shù)據(jù)列表的數(shù)量相同!?。? 列索引刪除數(shù)據(jù)列 通過 del 和 pop() 都能夠刪除 DataFrame 中的數(shù)據(jù)列
2.2.3 行索引操作DataFrame
理解了上述的列索引操作后,行索引操作就變的簡單。下面看一下,如何使用行索引來選取 DataFrame 中的數(shù)據(jù)。
標(biāo)簽索引選取 可以將行標(biāo)簽傳遞給 loc 函數(shù),來選取數(shù)據(jù)
dict_data = {
'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(dict_data)
print(df)
print(df.loc[..., "one"])
print(df.loc['b', 'one'])
代碼的運(yùn)行結(jié)果為:
one two
a 1.0 1
b 2.0 2
c 3.0 3
d NaN 4
a 1.0
b 2.0
c 3.0
d NaN
Name: one, dtype: float64
2.0
整數(shù)索引選取 通過將數(shù)據(jù)行所在的索引位置傳遞給 iloc 函數(shù),也可以實(shí)現(xiàn)數(shù)據(jù)行選取
dict_data = {
'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(dict_data)
print(df)
print(df.iloc[2])
print(df.iloc[1, :])
代碼的運(yùn)行結(jié)果為:
one two
a 1.0 1
b 2.0 2
c 3.0 3
d NaN 4
one 3.0
two 3.0
Name: c, dtype: float64
one 2.0
two 2.0
Name: b, dtype: float64
切片操作多行選取 可以使用切片的方式同時選取多行
dict_data = {
'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(dict_data)
print(df)
# 左閉右開
print(df[2:4])
代碼的運(yùn)行結(jié)果為:
one two
a 1.0 1
b 2.0 2
c 3.0 3
d NaN 4
one two
c 3.0 3
d NaN 4
添加數(shù)據(jù)行 使用 append() 函數(shù),可以將新的數(shù)據(jù)行添加到 DataFrame 中,該函數(shù)會在行末追加數(shù)據(jù)行
df = pd.DataFrame([[1, 2], [3, 4]], columns=['a', 'b'])
df2 = pd.DataFrame([[5, 6], [7, 8]], columns=['a', 'b'])
print("df\n", df)
print("df2\n", df2)
# 在行末追加新數(shù)據(jù)行
df = df._append(df2)
print(df)
代碼的運(yùn)行結(jié)果為:
df
a b
0 1 2
1 3 4
df2
a b
0 5 6
1 7 8
a b
0 1 2
1 3 4
0 5 6
1 7 8
刪除數(shù)據(jù)行 使用行索引標(biāo)簽,從 DataFrame 中刪除某一行數(shù)據(jù)。如果索引標(biāo)簽存在重復(fù),那么它們將被一起刪除
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)
# 注意此處調(diào)用了drop()方法
df = df.drop(0)
print(df)
代碼的運(yùn)行結(jié)果為:
a b
0 1 2
1 3 4
0 5 6
1 7 8
a b
1 3 4
1 7 8
2.2.4 DataFrame切片
直接使用中括號時:
索引優(yōu)先對列進(jìn)行操作 切片優(yōu)先對行進(jìn)行操作
dict_data = pd.DataFrame(
data=np.random.randint(60, 90, size=(5, 6)),
index=['張三', '李四', '王五', '趙六', '坤哥'],
columns=["語文", "數(shù)學(xué)", "英語", "地理", "歷史", "化學(xué)"]
)
print(dict_data)
# 行切片
print(dict_data[1:3])
print(dict_data["張三":"趙六"])
# 列切片
# 對列作切片,也必須先對行做切片
print(dict_data.iloc[:, 1:4])
print(dict_data.loc[:, "數(shù)學(xué)":"化學(xué)"])
# 對行和列作切片操作
print(dict_data.iloc[1:3, 1:4])
print(dict_data.loc["張三":"王五", "語文":"歷史"])
代碼的運(yùn)行結(jié)果為:
語文 數(shù)學(xué) 英語 地理 歷史 化學(xué)
張三 70 70 78 82 83 81
李四 69 64 74 72 76 70
王五 69 76 69 76 66 83
趙六 88 88 69 76 60 70
坤哥 65 74 84 79 60 72
語文 數(shù)學(xué) 英語 地理 歷史 化學(xué)
李四 69 64 74 72 76 70
王五 69 76 69 76 66 83
語文 數(shù)學(xué) 英語 地理 歷史 化學(xué)
張三 70 70 78 82 83 81
李四 69 64 74 72 76 70
王五 69 76 69 76 66 83
趙六 88 88 69 76 60 70
數(shù)學(xué) 英語 地理
張三 70 78 82
李四 64 74 72
王五 76 69 76
趙六 88 69 76
坤哥 74 84 79
數(shù)學(xué) 英語 地理 歷史 化學(xué)
張三 70 78 82 83 81
李四 64 74 72 76 70
王五 76 69 76 66 83
趙六 88 69 76 60 70
坤哥 74 84 79 60 72
數(shù)學(xué) 英語 地理
李四 64 74 72
王五 76 69 76
語文 數(shù)學(xué) 英語 地理 歷史
張三 70 70 78 82 83
李四 69 64 74 72 76
王五 69 76 69 76 66
Process finished with exit code 0
3 常用屬性和方法匯總
DataFrame 的屬性和方法,與 Series 相差無幾
名稱屬性&方法描述T行和列轉(zhuǎn)置。axes返回一個僅以行軸標(biāo)簽和列軸標(biāo)簽為成員的列表。dtypes返回每列數(shù)據(jù)的數(shù)據(jù)類型。emptyDataFrame中沒有數(shù)據(jù)或者任意坐標(biāo)軸的長度為0,則返回True。ndim軸的數(shù)量,也指數(shù)組的維數(shù)。shape返回一個元組,表示了 DataFrame 維度。sizeDataFrame中的元素數(shù)量。values使用 numpy 數(shù)組表示 DataFrame 中的元素值。head()返回前 n 行數(shù)據(jù)。tail()返回后 n 行數(shù)據(jù)。shift()將行或列移動指定的步幅長度
dict_data = {
'Name': pd.Series(['張三', '李四', "王五", '趙六', '坤哥', '凡凡', '峰峰']),
'age': pd.Series([25, 26, 25, 28, 23, 29, 23]),
'Height': pd.Series([174.23, 173.24, 173.98, 172.56, 183.20, 174.6, 183.8])
}
# 構(gòu)建DataFrame
df = pd.DataFrame(dict_data)
# 輸出series
print(df)
print("-*-" * 30)
# 輸出DataFrame的轉(zhuǎn)置,也就是把行和列進(jìn)行交換
print(df.T)
print("-*-" * 30)
# 返回一個行標(biāo)簽、列標(biāo)簽組成的列表
print(df.axes)
print("-*-" * 30)
# 輸出行、列標(biāo)簽類型
print(df.dtypes)
print("-*-" * 30)
# 判斷輸入數(shù)據(jù)是否為空,若為 True 表示對象為空
print("empty:\n", df.empty)
print("-*-" * 30)
# 返回數(shù)據(jù)對象的維數(shù)。DataFrame 是一個二維數(shù)據(jù)結(jié)構(gòu)
print(df.ndim)
print("-*-" * 30)
# DataFrame的形狀
print(df.shape)
print("-*-" * 30)
# DataFrame的中元素個數(shù)
print(df.size)
print("-*-" * 30)
# DataFrame的數(shù)據(jù)
print(df.values)
print("-*-" * 30)
# 獲取前3行數(shù)據(jù)
print(df.head(3))
print("-*-" * 30)
# 獲取后2行數(shù)據(jù)
print(df.tail(2))
代碼的運(yùn)行結(jié)果為:
Name age Height
0 張三 25 174.23
1 李四 26 173.24
2 王五 25 173.98
3 趙六 28 172.56
4 坤哥 23 183.20
5 凡凡 29 174.60
6 峰峰 23 183.80
-*--*--*--*--*--*--*--*--*--*--*--*--*--*--*--*--*--*--*--*--*--*--*--*--*--*--*--*--*--*-
0 1 2 3 4 5 6
Name 張三 李四 王五 趙六 坤哥 凡凡 峰峰
age 25 26 25 28 23 29 23
Height 174.23 173.24 173.98 172.56 183.2 174.6 183.8
-*--*--*--*--*--*--*--*--*--*--*--*--*--*--*--*--*--*--*--*--*--*--*--*--*--*--*--*--*--*-
[RangeIndex(start=0, stop=7, step=1), Index(['Name', 'age', 'Height'], dtype='object')]
-*--*--*--*--*--*--*--*--*--*--*--*--*--*--*--*--*--*--*--*--*--*--*--*--*--*--*--*--*--*-
Name object
age int64
Height float64
dtype: object
-*--*--*--*--*--*--*--*--*--*--*--*--*--*--*--*--*--*--*--*--*--*--*--*--*--*--*--*--*--*-
empty:
False
-*--*--*--*--*--*--*--*--*--*--*--*--*--*--*--*--*--*--*--*--*--*--*--*--*--*--*--*--*--*-
2
-*--*--*--*--*--*--*--*--*--*--*--*--*--*--*--*--*--*--*--*--*--*--*--*--*--*--*--*--*--*-
(7, 3)
-*--*--*--*--*--*--*--*--*--*--*--*--*--*--*--*--*--*--*--*--*--*--*--*--*--*--*--*--*--*-
21
-*--*--*--*--*--*--*--*--*--*--*--*--*--*--*--*--*--*--*--*--*--*--*--*--*--*--*--*--*--*-
[['張三' 25 174.23]
['李四' 26 173.24]
['王五' 25 173.98]
['趙六' 28 172.56]
['坤哥' 23 183.2]
['凡凡' 29 174.6]
['峰峰' 23 183.8]]
-*--*--*--*--*--*--*--*--*--*--*--*--*--*--*--*--*--*--*--*--*--*--*--*--*--*--*--*--*--*-
Name age Height
0 張三 25 174.23
1 李四 26 173.24
2 王五 25 173.98
-*--*--*--*--*--*--*--*--*--*--*--*--*--*--*--*--*--*--*--*--*--*--*--*--*--*--*--*--*--*-
Name age Height
5 凡凡 29 174.6
6 峰峰 23 183.8
shift()移動行或列 如果您想要移動 DataFrame 中的某一行/列,可以使用 shift() 函數(shù)實(shí)現(xiàn)。它提供了一個periods參數(shù),該參數(shù)表示在特定的軸上移動指定的步幅。
DataFrame.shift(periods=1, freq=None, axis=0)
?
# peroids 類型為int,表示移動的幅度,可以是正數(shù),也可以是負(fù)數(shù),默認(rèn)值為1。
# freq 日期偏移量,默認(rèn)值為None,適用于時間序。取值為符合時間規(guī)則的字符串。
# axis 如果是 0 或者 "index" 表示上下移動,如果是 1 或者 "columns" 則會左右移動。
# fill_value 該參數(shù)用來填充缺失值。
該函數(shù)的返回值是移動后的 DataFrame 副本
df = pd.DataFrame({
'a_data': [40, 28, 39, 32, 18],
'b_data': [20, 37, 41, 35, 45],
'c_data': [22, 17, 11, 25, 15]})
# 移動幅度為3
print(df)
new_df = df.shift(periods=1)
print(new_df)
print(df)
代碼的運(yùn)行結(jié)果為:
a_data b_data c_data
0 40 20 22
1 28 37 17
2 39 41 11
3 32 35 25
4 18 45 15
a_data b_data c_data
0 NaN NaN NaN
1 40.0 20.0 22.0
2 28.0 37.0 17.0
3 39.0 41.0 11.0
4 32.0 35.0 25.0
a_data b_data c_data
0 40 20 22
1 28 37 17
2 39 41 11
3 32 35 25
4 18 45 15
切記這里的shift,返回的是一個副本就類似于python中的深拷貝。shift函數(shù)在偏移數(shù)據(jù)時,并不會使原有的數(shù)據(jù)消失,而是將其移動到新的位置,并用NaN值填充原來的位置。
使用 fill_value 參數(shù)填充 DataFrame 中的缺失值
df = pd.DataFrame({
'a_data': [40, 28, 39, 32, 18],
'b_data': [20, 37, 41, 35, 45],
'c_data': [22, 17, 11, 25, 15]})
# 移動幅度為3
print(df)
new_df = df.shift(periods=3, axis="index", fill_value=100)
print(new_df)
代碼的運(yùn)行結(jié)果為:
a_data b_data c_data
0 40 20 22
1 28 37 17
2 39 41 11
3 32 35 25
4 18 45 15
a_data b_data c_data
0 100 100 100
1 100 100 100
2 100 100 100
3 40 20 22
柚子快報邀請碼778899分享:認(rèn)識pandas
相關(guān)鏈接
本文內(nèi)容根據(jù)網(wǎng)絡(luò)資料整理,出于傳遞更多信息之目的,不代表金鑰匙跨境贊同其觀點(diǎn)和立場。
轉(zhuǎn)載請注明,如有侵權(quán),聯(lián)系刪除。