Pandas DataFrame結(jié)構(gòu)

2023-05-11 15:48 更新

DataFrame 是 Pandas 的重要數(shù)據(jù)結(jié)構(gòu)之一,也是在使用 Pandas 進行數(shù)據(jù)分析過程中最常用的結(jié)構(gòu)之一,可以這么說,掌握了 DataFrame 的用法,你就擁有了學(xué)習(xí)數(shù)據(jù)分析的基本能力。

認(rèn)識DataFrame結(jié)構(gòu)

DataFrame 一個表格型的數(shù)據(jù)結(jié)構(gòu),既有行標(biāo)簽(index),又有列標(biāo)簽(columns),它也被稱異構(gòu)數(shù)據(jù)表,所謂異構(gòu),指的是表格中每列的數(shù)據(jù)類型可以不同,比如可以是字符串、整型或者浮點型等。其結(jié)構(gòu)圖示意圖,如下所示:

Dataframe結(jié)構(gòu)示意圖

表格中展示了某個銷售團隊個人信息和績效評級(rating)的相關(guān)數(shù)據(jù)。數(shù)據(jù)以行和列形式來表示,其中每一列表示一個屬性,而每一行表示一個條目的信息。

下表展示了上述表格中每一列標(biāo)簽所描述數(shù)據(jù)的數(shù)據(jù)類型,如下所示:

Column Type
name String
age integer
gender String
rating Float

DataFrame 的每一行數(shù)據(jù)都可以看成一個 Series 結(jié)構(gòu),只不過,DataFrame 為這些行中每個數(shù)據(jù)值增加了一個列標(biāo)簽。因此 DataFrame 其實是從 Series 的基礎(chǔ)上演變而來。在數(shù)據(jù)分析任務(wù)中 DataFrame 的應(yīng)用非常廣泛,因為它描述數(shù)據(jù)的更為清晰、直觀。

通過示例對  DataFrame 結(jié)構(gòu)做進一步講解。 下面展示了一張學(xué)生成績表,如下所示:

pandas dataframe結(jié)構(gòu)

DataFrame 結(jié)構(gòu)類似于 Execl 的表格型,表格中列標(biāo)簽的含義如下所示:

  • Regd.No:表示登記的序列號
  • Name:學(xué)生姓名
  • Marks:學(xué)生分?jǐn)?shù)

同 Series 一樣,DataFrame 自帶行標(biāo)簽索引,默認(rèn)為“隱式索引”即從 0 開始依次遞增,行標(biāo)簽與 DataFrame 中的數(shù)據(jù)項一一對應(yīng)。上述表格的行標(biāo)簽從 0 到 5,共記錄了 5 條數(shù)據(jù)(圖中將行標(biāo)簽省略)。當(dāng)然你也可以用“顯式索引”的方式來設(shè)置行標(biāo)簽。

下面對 DataFrame 數(shù)據(jù)結(jié)構(gòu)的特點做簡單地總結(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ù)運算。

創(chuàng)建DataFrame對象

創(chuàng)建 DataFrame 對象的語法格式如下:

import pandas as pd
pd.DataFrame( data, index, columns, dtype, copy)

參數(shù)說明:

參數(shù)名稱 說明
data 輸入的數(shù)據(jù),可以是 ndarray,series,list,dict,標(biāo)量以及一個 DataFrame。
index 行標(biāo)簽,如果沒有傳遞 index 值,則默認(rèn)行標(biāo)簽是 np.arange(n),n 代表 data 的元素個數(shù)。
columns 列標(biāo)簽,如果沒有傳遞 columns 值,則默認(rèn)列標(biāo)簽是 np.arange(n)。
dtype dtype表示每一列的數(shù)據(jù)類型。
copy 默認(rèn)為 False,表示復(fù)制數(shù)據(jù) data。

Pandas 提供了多種創(chuàng)建 DataFrame 對象的方式,主要包含以下五種,分別進行介紹。

1) 創(chuàng)建空的DataFrame對象

使用下列方式創(chuàng)建一個空的 DataFrame,這是 DataFrame 最基本的創(chuàng)建方法。

import pandas as pd
df = pd.DataFrame()
print(df)

輸出結(jié)果如下:

Empty DataFrame
Columns: []
Index: []

2) 列表創(chuàng)建DataFrame對象

可以使用單一列表或嵌套列表來創(chuàng)建一個 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 對象:

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ù)類型為 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

3) 字典嵌套列表創(chuàng)建

data 字典中,鍵對應(yīng)的值的元素長度必須相同(也就是列表長度相同)。如果傳遞了索引,那么索引的長度應(yīng)該等于數(shù)組的長度;如果沒有傳遞索引,那么默認(rèn)情況下,索引將是 range(n),其中 n 代表數(shù)組長度。

示例 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,并分別對應(yīng)了列表中的每個元素值。

示例 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ù)為每行分配了一個索引。

4) 列表嵌套字典創(chuàng)建DataFrame對象

列表嵌套字典可以作為輸入數(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

注意:如果其中某個元素值缺失,也就是字典的 key 無法找到對應(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)建一個 DataFrame 對象。

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

注意:因為 b1 在字典鍵中不存在,所以對應(yīng)值為 NaN。

5) Series創(chuàng)建DataFrame對象

您也可以傳遞一個字典形式的 Series,從而創(chuàng)建一個 DataFrame 對象,其輸出結(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

注意:對于 one 列而言,此處雖然顯示了行索引 'd',但由于沒有與其對應(yīng)的值,所以它的值為 NaN。

列索引操作DataFrame

DataFrame 可以使用列索(columns index)引來完成數(shù)據(jù)的選取、添加和刪除操作。下面依次對這些操作進行介紹。

1) 列索引選取數(shù)據(jù)列

您可以使用列索引,輕松實現(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

2) 列索引添加數(shù)據(jù)列

使用 columns 列索引表標(biāo)簽可以實現(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ù)列做相加運算
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ù)運算:
      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ù)運算,這和 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

3) 列索引刪除數(shù)據(jù)列

通過 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

行索引操作DataFrame

理解了上述的列索引操作后,行索引操作就變的簡單。下面看一下,如何使用行索引來選取 DataFrame 中的數(shù)據(jù)。

1) 標(biāo)簽索引選取

可以將行標(biāo)簽傳遞給 loc 函數(shù),來選取數(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é)果:

  1. one 2.0
  2. two 2.0
  3. Name: b, dtype: float64

注意:loc 允許接兩個參數(shù)分別是行和列,參數(shù)之間需要使用“逗號”隔開,但該函數(shù)只能接收標(biāo)簽索引。

2) 整數(shù)索引選取

通過將數(shù)據(jù)行所在的索引位置傳遞給 iloc 函數(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 允許接受兩個參數(shù)分別是行和列,參數(shù)之間使用“逗號”隔開,但該函數(shù)只能接收整數(shù)索引。

3) 切片操作多行選取

您也可以使用切片的方式同時選取多行。示例如下:

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])

輸出結(jié)果:

   one  two
c  3.0    3
d  NaN    4

4) 添加數(shù)據(jù)行

使用 append() 函數(shù),可以將新的數(shù)據(jù)行添加到 DataFrame 中,該函數(shù)會在行末追加數(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

5) 刪除數(shù)據(jù)行

您可以使用行索引標(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) 生成了行索引,并通過 drop(0) 同時刪除了兩行數(shù)據(jù)。

常用屬性和方法匯總

DataFrame 的屬性和方法,與 Series 相差無幾,如下所示:

名稱 屬性&方法描述
T 行和列轉(zhuǎn)置。
axes 返回一個僅以行軸標(biāo)簽和列軸標(biāo)簽為成員的列表。
dtypes 返回每列數(shù)據(jù)的數(shù)據(jù)類型。
empty DataFrame中沒有數(shù)據(jù)或者任意坐標(biāo)軸的長度為0,則返回True。
ndim 軸的數(shù)量,也指數(shù)組的維數(shù)。
shape 返回一個元組,表示了 DataFrame 維度。
size DataFrame中的元素數(shù)量。
values 使用 numpy 數(shù)組表示 DataFrame 中的元素值。
head() 返回前 n 行數(shù)據(jù)。
tail() 返回后 n 行數(shù)據(jù)。
shift() 將行或列移動指定的步幅長度

下面對 DataFrame 常用屬性進行演示,首先我們創(chuàng)建一個 DataFrame 對象,示例如下:

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

1) T(Transpose)轉(zhuǎn)置

返回 DataFrame 的轉(zhuǎ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

2) axes

返回一個行標(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')]

3) dtypes

返回每一列的數(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)
#輸出行、列標(biāo)簽
print(df.dtypes)

輸出結(jié)果:

Name       object
years       int64
Rating     float64
dtype:     object

4) empty

返回一個布爾值,判斷輸出的數(shù)據(jù)對象是否為空,若為 True 表示對象為空。

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é)果:

判斷輸入對象是否為空:
False

5) ndim

返回數(shù)據(jù)對象的維數(shù)。DataFrame 是一個二維數(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

6) shape

返回一個代表 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)

7) size

返回 DataFrame 中的元素數(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的中元素個數(shù)
print(df.size)

輸出結(jié)果:

21

8) values

以 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]]

9) head()&tail()查看數(shù)據(jù)

如果想要查看 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

10) shift()移動行或列

如果您想要移動 DataFrame 中的某一行/列,可以使用 shift() 函數(shù)實現(xiàn)。它提供了一個periods參數(shù),該參數(shù)表示在特定的軸上移動指定的步幅。

shif() 函數(shù)的語法格式如下:

DataFrame.shift(periods=1, freq=None, axis=0)  

參數(shù)說明如下:

參數(shù)名稱 說明
peroids 類型為int,表示移動的幅度,可以是正數(shù),也可以是負(fù)數(shù),默認(rèn)值為1。
freq 日期偏移量,默認(rèn)值為None,適用于時間序。取值為符合時間規(guī)則的字符串。
axis 如果是 0 或者 "index" 表示上下移動,如果是 1 或者 "columns" 則會左右移動。
fill_value 該參數(shù)用來填充缺失值。

該函數(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]}) 
#移動幅度為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]}) 
#移動幅度為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ù)不僅可以填充缺失值,還也可以對原數(shù)據(jù)進行替換。

以上內(nèi)容是否對您有幫助:
在線筆記
App下載
App下載

掃描二維碼

下載編程獅App

公眾號
微信公眾號

編程獅公眾號