DataFrame 是 Pandas 的重要數(shù)據(jù)結(jié)構(gòu)之一,也是在使用 Pandas 進(jìn)行數(shù)據(jù)分析過(guò)程中最常用的結(jié)構(gòu)之一,可以這么說(shuō),掌握了 DataFrame 的用法,你就擁有了學(xué)習(xí)數(shù)據(jù)分析的基本能力。
DataFrame 一個(gè)表格型的數(shù)據(jù)結(jié)構(gòu),既有行標(biāo)簽(index),又有列標(biāo)簽(columns),它也被稱(chēng)異構(gòu)數(shù)據(jù)表,所謂異構(gòu),指的是表格中每列的數(shù)據(jù)類(lèi)型可以不同,比如可以是字符串、整型或者浮點(diǎn)型等。其結(jié)構(gòu)圖示意圖,如下所示:
表格中展示了某個(gè)銷(xiāo)售團(tuán)隊(duì)個(gè)人信息和績(jī)效評(píng)級(jí)(rating)的相關(guān)數(shù)據(jù)。數(shù)據(jù)以行和列形式來(lái)表示,其中每一列表示一個(gè)屬性,而每一行表示一個(gè)條目的信息。
下表展示了上述表格中每一列標(biāo)簽所描述數(shù)據(jù)的數(shù)據(jù)類(lèi)型,如下所示:
Column | Type |
---|---|
name | String |
age | integer |
gender | String |
rating | Float |
DataFrame 的每一行數(shù)據(jù)都可以看成一個(gè) Series 結(jié)構(gòu),只不過(guò),DataFrame 為這些行中每個(gè)數(shù)據(jù)值增加了一個(gè)列標(biāo)簽。因此 DataFrame 其實(shí)是從 Series 的基礎(chǔ)上演變而來(lái)。在數(shù)據(jù)分析任務(wù)中 DataFrame 的應(yīng)用非常廣泛,因?yàn)樗枋鰯?shù)據(jù)的更為清晰、直觀。
通過(guò)示例對(duì) DataFrame 結(jié)構(gòu)做進(jìn)一步講解。 下面展示了一張學(xué)生成績(jī)表,如下所示:
DataFrame 結(jié)構(gòu)類(lèi)似于 Execl 的表格型,表格中列標(biāo)簽的含義如下所示:
同 Series 一樣,DataFrame 自帶行標(biāo)簽索引,默認(rèn)為“隱式索引”即從 0 開(kāi)始依次遞增,行標(biāo)簽與 DataFrame 中的數(shù)據(jù)項(xiàng)一一對(duì)應(yīng)。上述表格的行標(biāo)簽從 0 到 5,共記錄了 5 條數(shù)據(jù)(圖中將行標(biāo)簽省略)。當(dāng)然你也可以用“顯式索引”的方式來(lái)設(shè)置行標(biāo)簽。
下面對(duì) DataFrame 數(shù)據(jù)結(jié)構(gòu)的特點(diǎn)做簡(jiǎn)單地總結(jié),如下所示:
創(chuàng)建 DataFrame 對(duì)象的語(yǔ)法格式如下:
import pandas as pd
pd.DataFrame( data, index, columns, dtype, copy)
參數(shù)說(shuō)明:
參數(shù)名稱(chēng) | 說(shuō)明 |
---|---|
data | 輸入的數(shù)據(jù),可以是 ndarray,series,list,dict,標(biāo)量以及一個(gè) DataFrame。 |
index | 行標(biāo)簽,如果沒(méi)有傳遞 index 值,則默認(rèn)行標(biāo)簽是 np.arange(n),n 代表 data 的元素個(gè)數(shù)。 |
columns | 列標(biāo)簽,如果沒(méi)有傳遞 columns 值,則默認(rèn)列標(biāo)簽是 np.arange(n)。 |
dtype | dtype表示每一列的數(shù)據(jù)類(lèi)型。 |
copy | 默認(rèn)為 False,表示復(fù)制數(shù)據(jù) data。 |
Pandas 提供了多種創(chuàng)建 DataFrame 對(duì)象的方式,主要包含以下五種,分別進(jìn)行介紹。
1) 創(chuàng)建空的DataFrame對(duì)象
使用下列方式創(chuàng)建一個(gè)空的 DataFrame,這是 DataFrame 最基本的創(chuàng)建方法。
import pandas as pd
df = pd.DataFrame()
print(df)
輸出結(jié)果如下:
Empty DataFrame Columns: [] Index: []
可以使用單一列表或嵌套列表來(lái)創(chuàng)建一個(gè) DataFrame。
示例 1,單一列表創(chuàng)建 DataFrame:
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,使用嵌套列表創(chuàng)建 DataFrame 對(duì)象:
import pandas as pd
data = [['Alex',10],['Bob',12],['Clarke',13]]
df = pd.DataFrame(data,columns=['Name','Age'])
print(df)
輸出結(jié)果:
Name Age 0 Alex 10 1 Bob 12 2 Clarke 13
示例 3,指定數(shù)值元素的數(shù)據(jù)類(lèi)型為 float:
import pandas as pd
data = [['Alex',10],['Bob',12],['Clarke',13]]
df = pd.DataFrame(data,columns=['Name','Age'],dtype=float)
print(df)
輸出結(jié)果:
Name Age 0 Alex 10.0 1 Bob 12.0 2 Clarke 13.0
data 字典中,鍵對(duì)應(yīng)的值的元素長(zhǎng)度必須相同(也就是列表長(zhǎng)度相同)。如果傳遞了索引,那么索引的長(zhǎng)度應(yīng)該等于數(shù)組的長(zhǎng)度;如果沒(méi)有傳遞索引,那么默認(rèn)情況下,索引將是 range(n),其中 n 代表數(shù)組長(zhǎng)度。
示例 4:
import pandas as pd
data = {'Name':['Tom', 'Jack', 'Steve', 'Ricky'],'Age':[28,34,29,42]}
df = pd.DataFrame(data)
print(df)
輸出結(jié)果:
Age Name 0 28 Tom 1 34 Jack 2 29 Steve 3 42 Ricky
注意:這里使用了默認(rèn)行標(biāo)簽,也就是 range(n)。它生成了 0,1,2,3,并分別對(duì)應(yīng)了列表中的每個(gè)元素值。
示例 5,現(xiàn)在給上述示例 4 添加自定義的行標(biāo)簽:
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)
輸出結(jié)果如下:
Age Name rank1 28 Tom rank2 34 Jack rank3 29 Steve rank4 42 Ricky
注意:index 參數(shù)為每行分配了一個(gè)索引。
列表嵌套字典可以作為輸入數(shù)據(jù)傳遞給 DataFrame 構(gòu)造函數(shù)。默認(rèn)情況下,字典的鍵被用作列名。
示例 6 如下:
import pandas as pd
data = [{'a': 1, 'b': 2},{'a': 5, 'b': 10, 'c': 20}]
df = pd.DataFrame(data)
print(df)
輸出結(jié)果:
a b c 0 1 2 NaN 1 5 10 20.0
注意:如果其中某個(gè)元素值缺失,也就是字典的 key 無(wú)法找到對(duì)應(yīng)的 value,將使用 NaN 代替。
示例 7,給上述示例 6 添加行標(biāo)簽索引:
import pandas as pd
data = [{'a': 1, 'b': 2},{'a': 5, 'b': 10, 'c': 20}]
df = pd.DataFrame(data, index=['first', 'second'])
print(df)
輸出結(jié)果:
a b c first 1 2 NaN second 5 10 20.0
示例 8,如何使用字典嵌套列表以及行、列索引表創(chuàng)建一個(gè) DataFrame 對(duì)象。
import pandas as pd
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'])
print(df1)
print(df2)
輸出結(jié)果:
#df1輸出 a b first 1 2 second 5 10 #df2輸出 a b1 first 1 NaN second 5 NaN
注意:因?yàn)?b1 在字典鍵中不存在,所以對(duì)應(yīng)值為 NaN。
您也可以傳遞一個(gè)字典形式的 Series,從而創(chuàng)建一個(gè) DataFrame 對(duì)象,其輸出結(jié)果的行索引是所有 index 的合集。 示例如下:
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)
輸出結(jié)果如下:
one two a 1.0 1 b 2.0 2 c 3.0 3 d NaN 4
注意:對(duì)于 one 列而言,此處雖然顯示了行索引 'd',但由于沒(méi)有與其對(duì)應(yīng)的值,所以它的值為 NaN。
DataFrame 可以使用列索(columns index)引來(lái)完成數(shù)據(jù)的選取、添加和刪除操作。下面依次對(duì)這些操作進(jìn)行介紹。
您可以使用列索引,輕松實(shí)現(xiàn)數(shù)據(jù)選取,示例如下:
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'])
輸出結(jié)果:
a 1.0 b 2.0 c 3.0 d NaN Name: one, dtype: float64
使用 columns 列索引表標(biāo)簽可以實(shí)現(xiàn)添加新的數(shù)據(jù)列,示例如下:
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['列']=值,插入新的數(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)
輸出結(jié)果:
使用列索引創(chuàng)建新數(shù)據(jù)列: 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 已存在的數(shù)據(jù)列做算術(shù)運(yùn)算: 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
上述示例,我們初次使用了 DataFrame 的算術(shù)運(yùn)算,這和 NumPy 非常相似。除了使用df[]=value的方式外,您還可以使用 insert() 方法插入新的列,示例如下:
import pandas as pd
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)
輸出結(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
通過(guò) del 和 pop() 都能夠刪除 DataFrame 中的數(shù)據(jù)列。示例如下:
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)
#使用del刪除
del df['one']
print(df)
#使用pop方法刪除
df.pop('two')
print(df)
輸出結(jié)果:
原DataFrame: 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 使用del刪除 first: three two a 10.0 1 b 20.0 2 c 30.0 3 d NaN 4 使用 pop()刪除: three a 10.0 b 20.0 c 30.0 d NaN
理解了上述的列索引操作后,行索引操作就變的簡(jiǎn)單。下面看一下,如何使用行索引來(lái)選取 DataFrame 中的數(shù)據(jù)。
可以將行標(biāo)簽傳遞給 loc 函數(shù),來(lái)選取數(shù)據(jù)。示例如下:
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'])
輸出結(jié)果:
- one 2.0
- two 2.0
- Name: b, dtype: float64
注意:loc 允許接兩個(gè)參數(shù)分別是行和列,參數(shù)之間需要使用“逗號(hào)”隔開(kāi),但該函數(shù)只能接收標(biāo)簽索引。
通過(guò)將數(shù)據(jù)行所在的索引位置傳遞給 iloc 函數(shù),也可以實(shí)現(xiàn)數(shù)據(jù)行選取。示例如下:
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])
輸出結(jié)果:
one 3.0 two 3.0 Name: c, dtype: float64
注意:iloc 允許接受兩個(gè)參數(shù)分別是行和列,參數(shù)之間使用“逗號(hào)”隔開(kāi),但該函數(shù)只能接收整數(shù)索引。
您也可以使用切片的方式同時(shí)選取多行。示例如下:
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)
#左閉右開(kāi)
print(df[2:4])
輸出結(jié)果:
one two c 3.0 3 d NaN 4
使用 append() 函數(shù),可以將新的數(shù)據(jù)行添加到 DataFrame 中,該函數(shù)會(huì)在行末追加數(shù)據(jù)行。示例如下:
import pandas as pd
df = pd.DataFrame([[1, 2], [3, 4]], columns = ['a','b'])
df2 = pd.DataFrame([[5, 6], [7, 8]], columns = ['a','b'])
#在行末追加新數(shù)據(jù)行
df = df.append(df2)
print(df)
輸出結(jié)果:
a b 0 1 2 1 3 4 0 5 6 1 7 8
您可以使用行索引標(biāo)簽,從 DataFrame 中刪除某一行數(shù)據(jù)。如果索引標(biāo)簽存在重復(fù),那么它們將被一起刪除。示例如下:
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)
#注意此處調(diào)用了drop()方法
df = df.drop(0)
print(df)
輸出結(jié)果:
執(zhí)行drop(0)前: a b 0 1 2 1 3 4 0 5 6 1 7 8 執(zhí)行drop(0)后: a b 1 3 4 1 7 8
在上述的示例中,默認(rèn)使用 range(2) 生成了行索引,并通過(guò) drop(0) 同時(shí)刪除了兩行數(shù)據(jù)。
DataFrame 的屬性和方法,與 Series 相差無(wú)幾,如下所示:
名稱(chēng) | 屬性&方法描述 |
---|---|
T | 行和列轉(zhuǎn)置。 |
axes | 返回一個(gè)僅以行軸標(biāo)簽和列軸標(biāo)簽為成員的列表。 |
dtypes | 返回每列數(shù)據(jù)的數(shù)據(jù)類(lèi)型。 |
empty | DataFrame中沒(méi)有數(shù)據(jù)或者任意坐標(biāo)軸的長(zhǎng)度為0,則返回True。 |
ndim | 軸的數(shù)量,也指數(shù)組的維數(shù)。 |
shape | 返回一個(gè)元組,表示了 DataFrame 維度。 |
size | DataFrame中的元素?cái)?shù)量。 |
values | 使用 numpy 數(shù)組表示 DataFrame 中的元素值。 |
head() | 返回前 n 行數(shù)據(jù)。 |
tail() | 返回后 n 行數(shù)據(jù)。 |
shift() | 將行或列移動(dòng)指定的步幅長(zhǎng)度 |
下面對(duì) DataFrame 常用屬性進(jìn)行演示,首先我們創(chuàng)建一個(gè) DataFrame 對(duì)象,示例如下:
import pandas as pd
import numpy as np
d = {'Name':pd.Series(['W3Cschool','編程獅',"百度",'360搜索','谷歌','微學(xué)苑','Bing搜索']),
'years':pd.Series([5,6,15,28,3,19,23]),
'Rating':pd.Series([4.23,3.24,3.98,2.56,3.20,4.6,3.8])}
#構(gòu)建DataFrame
df = pd.DataFrame(d)
#輸出series
print(df)
輸出結(jié)果:
輸出 series 數(shù)據(jù): Name years Rating 0 W3Cschool 5 4.23 1 編程獅 6 3.24 2 百度 15 3.98 3 360搜索 28 2.56 4 谷歌 3 3.20 5 微學(xué)苑 19 4.60 6 Bing搜索 23 3.80
返回 DataFrame 的轉(zhuǎn)置,也就是把行和列進(jìn)行交換。
import pandas as pd
import numpy as np
d = {'Name':pd.Series(['W3Cschool','編程獅',"百度",'360搜索','谷歌','微學(xué)苑','Bing搜索']),
'years':pd.Series([5,6,15,28,3,19,23]),
'Rating':pd.Series([4.23,3.24,3.98,2.56,3.20,4.6,3.8])}
#構(gòu)建DataFrame
df = pd.DataFrame(d)
#輸出DataFrame的轉(zhuǎn)置
print(df.T)
輸出結(jié)果:
Our data series is: 0 1 2 3 4 5 6 Name W3Cschool 編程獅 百度 360搜索 谷歌 微學(xué)苑 Bing搜索 years 5 6 15 28 3 19 23 Rating 4.23 3.24 3.98 2.56 3.2 4.6 3.8
返回一個(gè)行標(biāo)簽、列標(biāo)簽組成的列表。
import pandas as pd
import numpy as np
d = {'Name':pd.Series(['W3Cschool','編程獅',"百度",'360搜索','谷歌','微學(xué)苑','Bing搜索']),
'years':pd.Series([5,6,15,28,3,19,23]),
'Rating':pd.Series([4.23,3.24,3.98,2.56,3.20,4.6,3.8])}
#構(gòu)建DataFrame
df = pd.DataFrame(d)
#輸出行、列標(biāo)簽
print(df.axes)
輸出結(jié)果:
[RangeIndex(start=0, stop=7, step=1), Index(['Name', 'years', 'Rating'], dtype='object')]
返回每一列的數(shù)據(jù)類(lèi)型。示例如下:
import pandas as pd
import numpy as np
d = {'Name':pd.Series(['W3Cschool','編程獅',"百度",'360搜索','谷歌','微學(xué)苑','Bing搜索']),
'years':pd.Series([5,6,15,28,3,19,23]),
'Rating':pd.Series([4.23,3.24,3.98,2.56,3.20,4.6,3.8])}
#構(gòu)建DataFrame
df = pd.DataFrame(d)
#輸出行、列標(biāo)簽
print(df.dtypes)
輸出結(jié)果:
Name object years int64 Rating float64 dtype: object
返回一個(gè)布爾值,判斷輸出的數(shù)據(jù)對(duì)象是否為空,若為 True 表示對(duì)象為空。
import pandas as pd
import numpy as np
d = {'Name':pd.Series(['W3CSchool','編程獅',"百度",'360搜索','谷歌','微學(xué)苑','Bing搜索']),
'years':pd.Series([5,6,15,28,3,19,23]),
'Rating':pd.Series([4.23,3.24,3.98,2.56,3.20,4.6,3.8])}
#構(gòu)建DataFrame
df = pd.DataFrame(d)
#判斷輸入數(shù)據(jù)是否為空
print(df.empty)
輸出結(jié)果:
判斷輸入對(duì)象是否為空: False
返回?cái)?shù)據(jù)對(duì)象的維數(shù)。DataFrame 是一個(gè)二維數(shù)據(jù)結(jié)構(gòu)。
import pandas as pd
import numpy as np
d = {'Name':pd.Series(['W3Cschool','編程獅',"百度",'360搜索','谷歌','微學(xué)苑','Bing搜索']),
'years':pd.Series([5,6,15,28,3,19,23]),
'Rating':pd.Series([4.23,3.24,3.98,2.56,3.20,4.6,3.8])}
#構(gòu)建DataFrame
df = pd.DataFrame(d)
#DataFrame的維度
print(df.ndim)
輸出結(jié)果:
2
返回一個(gè)代表 DataFrame 維度的元組。返回值元組 (a,b),其中 a 表示行數(shù),b 表示列數(shù)。
import pandas as pd
import numpy as np
d = {'Name':pd.Series(['W3Cschool','編程獅',"百度",'360搜索','谷歌','微學(xué)苑','Bing搜索']),
'years':pd.Series([5,6,15,28,3,19,23]),
'Rating':pd.Series([4.23,3.24,3.98,2.56,3.20,4.6,3.8])}
#構(gòu)建DataFrame
df = pd.DataFrame(d)
#DataFrame的形狀
print(df.shape)
輸出結(jié)果:
(7, 3)
返回 DataFrame 中的元素?cái)?shù)量。示例如下:
import pandas as pd
import numpy as np
d = {'Name':pd.Series(['W3Cschool','編程獅',"百度",'360搜索','谷歌','微學(xué)苑','Bing搜索']),
'years':pd.Series([5,6,15,28,3,19,23]),
'Rating':pd.Series([4.23,3.24,3.98,2.56,3.20,4.6,3.8])}
#構(gòu)建DataFrame
df = pd.DataFrame(d)
#DataFrame的中元素個(gè)數(shù)
print(df.size)
輸出結(jié)果:
21
以 ndarray 數(shù)組的形式返回 DataFrame 中的數(shù)據(jù)。
import pandas as pd
import numpy as np
d = {'Name':pd.Series(['W3Cschool','編程獅',"百度",'360搜索','谷歌','微學(xué)苑','Bing搜索']),
'years':pd.Series([5,6,15,28,3,19,23]),
'Rating':pd.Series([4.23,3.24,3.98,2.56,3.20,4.6,3.8])}
#構(gòu)建DataFrame
df = pd.DataFrame(d)
#DataFrame的數(shù)據(jù)
print(df.values)
輸出結(jié)果:
[['W3Cschool' 5 4.23] ['編程獅' 6 3.24] ['百度' 15 3.98] ['360搜索' 28 2.56] ['谷歌' 3 3.2] ['微學(xué)苑' 19 4.6] ['Bing搜索' 23 3.8]]
如果想要查看 DataFrame 的一部分?jǐn)?shù)據(jù),可以使用 head() 或者 tail() 方法。其中 head() 返回前 n 行數(shù)據(jù),默認(rèn)顯示前 5 行數(shù)據(jù)。示例如下:
import pandas as pd
import numpy as np
d = {'Name':pd.Series(['W3CSchool','編程獅',"百度",'360搜索','谷歌','微學(xué)苑','Bing搜索']),
'years':pd.Series([5,6,15,28,3,19,23]),
'Rating':pd.Series([4.23,3.24,3.98,2.56,3.20,4.6,3.8])}
#構(gòu)建DataFrame
df = pd.DataFrame(d)
#獲取前3行數(shù)據(jù)
print(df.head(3))
輸出結(jié)果:
Name years Rating 0 W3CSchool 5 4.23 1 編程獅 6 3.24 2 百度 15 3.98
tail() 返回后 n 行數(shù)據(jù),示例如下:
import pandas as pd
import numpy as np
d = {'Name':pd.Series(['W3CSchool','編程獅',"百度",'360搜索','谷歌','微學(xué)苑','Bing搜索']),
'years':pd.Series([5,6,15,28,3,19,23]),
'Rating':pd.Series([4.23,3.24,3.98,2.56,3.20,4.6,3.8])}
#構(gòu)建DataFrame
df = pd.DataFrame(d)
#獲取后2行數(shù)據(jù)
print(df.tail(2))
輸出結(jié)果:
Name years Rating 5 微學(xué)苑 19 4.6 6 Bing搜索 23 3.8
如果您想要移動(dòng) DataFrame 中的某一行/列,可以使用 shift() 函數(shù)實(shí)現(xiàn)。它提供了一個(gè)periods參數(shù),該參數(shù)表示在特定的軸上移動(dòng)指定的步幅。
shif() 函數(shù)的語(yǔ)法格式如下:
DataFrame.shift(periods=1, freq=None, axis=0)
參數(shù)說(shuō)明如下:
參數(shù)名稱(chēng) | 說(shuō)明 |
---|---|
peroids | 類(lèi)型為int,表示移動(dòng)的幅度,可以是正數(shù),也可以是負(fù)數(shù),默認(rèn)值為1。 |
freq | 日期偏移量,默認(rèn)值為None,適用于時(shí)間序。取值為符合時(shí)間規(guī)則的字符串。 |
axis | 如果是 0 或者 "index" 表示上下移動(dòng),如果是 1 或者 "columns" 則會(huì)左右移動(dòng)。 |
fill_value | 該參數(shù)用來(lái)填充缺失值。 |
該函數(shù)的返回值是移動(dòng)后的 DataFrame 副本。下面看一組簡(jiǎn)單的實(shí)例:
import pandas as pd
info= pd.DataFrame({'a_data': [40, 28, 39, 32, 18],
'b_data': [20, 37, 41, 35, 45],
'c_data': [22, 17, 11, 25, 15]})
#移動(dòng)幅度為3
info.shift(periods=3)
輸出結(jié)果:
a_data b_data c_data 0 NaN NaN NaN 1 NaN NaN NaN 2 NaN NaN NaN 3 40.0 20.0 22.0 4 28.0 37.0 17.0
下面使用 fill_value 參數(shù)填充 DataFrame 中的缺失值,如下所示:
import pandas as pd
info= pd.DataFrame({'a_data': [40, 28, 39, 32, 18],
'b_data': [20, 37, 41, 35, 45],
'c_data': [22, 17, 11, 25, 15]})
#移動(dòng)幅度為3
print(info.shift(periods=3))
#將缺失值和原數(shù)值替換為52
info.shift(periods=3,axis=1,fill_value= 52)
輸出結(jié)果:
原輸出結(jié)果: a_data b_data c_data 0 NaN NaN NaN 1 NaN NaN NaN 2 NaN NaN NaN 3 40.0 20.0 22.0 4 28.0 37.0 17.0 替換后輸出: a_data b_data c_data 0 52 52 52 1 52 52 52 2 52 52 52 3 52 52 52 4 52 52 52
注意:fill_value 參數(shù)不僅可以填充缺失值,還也可以對(duì)原數(shù)據(jù)進(jìn)行替換。
更多建議: