pandas索引对象

一、什么是索引对象

        索引对象的理解其实很简单,索引对象的作用主要是负责管理轴标签和其他元数据的。构建Series和DataFrame时,所用到的任何数组或其他序列的标签都会被转换成一个Index。pandas中Index类来表示基本索引对象。来看两个打印,分别是索引对象所在类名输出,一个是其__doc__属性。

import pandas as pd
import numpy as np

print(pd.Index)
print(pd.Index.__doc__)

二、索引对象的获取

import pandas as pd
import numpy as np

a = pd.Index([1, 2, 3])
b = pd.Index(list('abc'))
print(a)
print(b)


"""
结果

Index([1, 2, 3], dtype='int64')
Index(['a', 'b', 'c'], dtype='object')
"""

        我们来看一下上述输出的最后有两个例子,即使用pd.Index()方法就能创建一个索引对象。第一个输出dtype='int64',第二个dtype='object',第二个输出难道不是dtype='string',要回答这个问题,我们先看另外一个例子:

import pandas as pd
import numpy as np

data_test = pd.DataFrame({"Yes_No": [True, False],
                          "Value": [1.1, 2],
                          "Type": ['Small', 'large']
                          })
print(data_test.dtypes)


"""
结果

Yes_No       bool
Value     float64
Type       object
dtype: object
"""

        “Type”行数据的类型为object,并不是String,跟索引对象中的一致,这是为什么呢?简单的说就是:dtype对象来自NumPy,它描述ndarray中元素的类型。ndarray中的每个元素都必须具有相同的字节大小。对于int64和float64,它们是8个字节。但是对于字符串,字符串的长度不是固定的,Pandas使用了一个对象ndarray来保存指向对象的指针,而不是直接在ndarray中保存字符串的字节,因此这种ndarray的dtype是object。

        弄清楚这个问题,我们就可以看一下索引对象怎么获取了:

import pandas as pd
import numpy as np

df = pd.DataFrame({'time': ['2023-09-21', '2023-09-22', '2023-09-23'],
                   'count': [1, 2, 3]}, index=['a', 'b', 'c'])
print(df)
print('获取的索引对象为:', df.index)
print('获取的索引对象值为:', df.index.values)


"""
结果

         time  count
a  2023-09-21      1
b  2023-09-22      2
c  2023-09-23      3
获取的索引对象为: Index(['a', 'b', 'c'], dtype='object')
获取的索引对象值为: ['a' 'b' 'c']
"""

        使用df.index获取索引对象,使用df.index.values获取索引对象数据。 

三、索引的可重复性

        索引对象的索引是可以重复的,这句话是什么意思呢?我们在构建DataFrame的时候传入的index是可以重复的,可以这样: index=['a','b','c'],可以这样index=['a','b','a'],还可以这样index=['a','a',None]等等。

import pandas as pd
import numpy as np

df = pd.DataFrame({'time': ['2023-09-21', '2023-09-22', '2023-09-23', '2023-09-24'],
                   'count': [1, 2, 3, 4]}, index=['a', 'b', 'a', 'b'])
print(df)
print(df.index.is_unique)
print(df.index.isna())


"""
结果

         time  count
a  2023-09-21      1
b  2023-09-22      2
a  2023-09-23      3
b  2023-09-24      4
False
[False False False False]
"""

        第一行输出包含重复索引的DataFrame。

        第二行代码使用is_unique()方法来判断索引是否是唯一不重复的,返回bool值。

        第三行代码使用isna()方法来判断索引是否是None值。

四、索引的不可修改性

        索引的不可修改性就是说这个索引是不支持进行修改的,但是可以进行重置。换句话说索引是不支持部分修改的,可以全部替换。

import pandas as pd
import numpy as np

df = pd.DataFrame({'time': ['2023-09-21', '2023-09-22', '2023-09-23', '2023-09-24'],
                   'count': [1, 2, 3, 4]}, index=['a', 'b', 'a', 'b'])
print(df.index[0])
df.index[0] = "p"


"""
结果

报错:
    TypeError: Index does not support mutable operations
"""

        那么该如何进行这个索引的修改的呢?介绍重置索引的方法: 

1. 直接赋值替换

import pandas as pd
import numpy as np

df = pd.DataFrame({'time': ['2023-09-21', '2023-09-22', '2023-09-23', '2023-09-24'],
                   'count': [1, 2, 3, 4]}, index=['a', 'b', 'a', 'b'])
df.index = ['e', 'r', 't', 'y']
print(df)


"""
#结果


         time  count
e  2023-09-21      1
r  2023-09-22      2
t  2023-09-23      3
y  2023-09-24      4

#替换索引成功
"""

2.使用set_index(),reset_index()和reindex()方法

        在pandas中常用的有几个方法如set_index() 和 reset_index() 以及 reindex() ,这几个方法看着很相近但是如果没有完全搞明白区分它们的不同的话,在日后的使用中会极大影响数据预处理时的工作效率。为了更好的以不同例子说明这几个方法的作用与区别,如下先声明一个初始数据集。

import pandas as pd
import numpy as np

# 生成模拟数据
generd = ['男', '女']
boolean = [True, False]

df = pd.DataFrame({"height": np.random.randint(150, 190, 5),
                   "weight": np.random.randint(40, 80, 5),
                   "age": np.random.randint(20, 100, 5),
                   "gender": [generd[x] for x in np.random.randint(0, len(generd), 5)],
                   "smoker": [boolean[x] for x in np.random.randint(0, 2, 5)]
                   },
                  index=list("abcde"))
print(df)

"""
#结果

   height  weight  age gender  smoker
a     172      61   65      女    True
b     187      77   57      女    True
c     177      48   52      男    True
d     167      57   39      女    True
e     162      73   65      女    True

"""

(1)set_index()

DataFrame.set_index(keys, drop=True, append=False, inplace=False, verify_integrity=False)

        set_index() 主要可以将数据表中指定的某列设置为索引或复合索引,如下是常涉及使用的几个参数:

                keys:列标签或列标签/数组列表,需要设置为索引的列。

                drop:默认为True,删除用作新索引的列,也就是当把某列设置为索引后,原来的列会移除。

                append:是否将列附加到现有索引,默认为False。

                inplace:输入布尔值,表示当前操作是否对原数据生效,默认为False。

        如下代码说明,当keys参数设置为height字段时,height字段将变成索引列。同时因为drop=True 代表同时删除原数据中的height列,默认情况本身为True。

import pandas as pd
import numpy as np

# 生成模拟数据
generd = ['男', '女']
boolean = [True, False]

df = pd.DataFrame({"height": np.random.randint(150, 190, 5),
                   "weight": np.random.randint(40, 80, 5),
                   "age": np.random.randint(20, 100, 5),
                   "gender": [generd[x] for x in np.random.randint(0, len(generd), 5)],
                   "smoker": [boolean[x] for x in np.random.randint(0, 2, 5)]
                   },
                  index=list("abcde"))

df01 = df.set_index(keys="height",drop=True)
print(df01)

"""
#结果

        weight  age gender  smoker
height                            
176         75   34      男   False
182         54   62      女   False
154         75   79      男   False
161         79   28      男    True
150         62   33      女    True


"""

        当drop=False时,保留了原数据中的height列:

import pandas as pd
import numpy as np

# 生成模拟数据
generd = ['男', '女']
boolean = [True, False]

df = pd.DataFrame({"height": np.random.randint(150, 190, 5),
                   "weight": np.random.randint(40, 80, 5),
                   "age": np.random.randint(20, 100, 5),
                   "gender": [generd[x] for x in np.random.randint(0, len(generd), 5)],
                   "smoker": [boolean[x] for x in np.random.randint(0, 2, 5)]
                   },
                  index=list("abcde"))

df01 = df.set_index(keys="height", drop=False)
print(df01)

"""
#结果

        weight  age gender  smoker
height                            
176         75   34      男   False
182         54   62      女   False
154         75   79      男   False
161         79   28      男    True
150         62   33      女    True


"""

new_index = df01.index.rename("这是索引")
print(new_index)
df01.index = new_index
print(df01)


"""
#结果

Index([188, 150, 156, 151, 189], dtype='int32', name='这是索引')
      height  weight  age gender  smoker
这是索引                                    
188      188      55   33      女    True
150      150      77   21      女    True
156      156      61   97      男   False
151      151      67   72      男    True
189      189      77   73      女    True

"""

        如下代码与之前的代码基本相似,也是将height字段将变成索引列。同时drop=False,代表保留原数据中的该列。但有明显不同之处是设置了append=True,这就代表将height列是以添加的额外附加的形式添加到现有索引中,但并不会把原来最初的索引移除。

import pandas as pd
import numpy as np

# 生成模拟数据
generd = ['男', '女']
boolean = [True, False]

df = pd.DataFrame({"height": np.random.randint(150, 190, 5),
                   "weight": np.random.randint(40, 80, 5),
                   "age": np.random.randint(20, 100, 5),
                   "gender": [generd[x] for x in np.random.randint(0, len(generd), 5)],
                   "smoker": [boolean[x] for x in np.random.randint(0, 2, 5)]
                   },
                  index=list("abcde"))
print(df)
print("===============================================")
df01 = df.set_index(keys="height", drop=False, append=True)
print(df01)

"""
#结果

   height  weight  age gender  smoker
a     175      79   92      男    True
b     182      51   97      女   False
c     151      63   27      女    True
d     168      41   47      男   False
e     177      61   58      男   False
===============================================
          height  weight  age gender  smoker
  height                                    
a 175        175      79   92      男    True
b 182        182      51   97      女   False
c 151        151      63   27      女    True
d 168        168      41   47      男   False
e 177        177      61   58      男   False

"""

        可以看到正因为之前使用了append参数以附加索引的方式添加,如下当查看index索引时会发现得到的索引是复合索引。 

import pandas as pd
import numpy as np

# 生成模拟数据
generd = ['男', '女']
boolean = [True, False]

df = pd.DataFrame({"height": np.random.randint(150, 190, 5),
                   "weight": np.random.randint(40, 80, 5),
                   "age": np.random.randint(20, 100, 5),
                   "gender": [generd[x] for x in np.random.randint(0, len(generd), 5)],
                   "smoker": [boolean[x] for x in np.random.randint(0, 2, 5)]
                   },
                  index=list("abcde"))
print(df)
print("===============================================")
df01 = df.set_index(keys="height", drop=False, append=True)
print(df01)
print("===============================================")
print(df01.index)

"""
#结果

   height  weight  age gender  smoker
a     182      53   41      女    True
b     163      60   70      女    True
c     178      51   57      女    True
d     182      77   54      女   False
e     173      55   46      男   False
===============================================
          height  weight  age gender  smoker
  height                                    
a 182        182      53   41      女    True
b 163        163      60   70      女    True
c 178        178      51   57      女    True
d 182        182      77   54      女   False
e 173        173      55   46      男   False
===============================================
MultiIndex([('a', 182),
            ('b', 163),
            ('c', 178),
            ('d', 182),
            ('e', 173)],
           names=[None, 'height'])

"""

(2)reset_index()

         reset_index() 主要可以将数据表中的索引还原为普通列并重新变为默认的整型索引。如下是常涉及使用的几个参数:

                level:数值类型可以为:int、str、tuple或list,默认无,仅从索引中删除给定级别。默认情况下移除所有级别。控制了具体要还原的那个等级的索引 。

                drop:当指定drop=False(默认为False)时,则索引列会被还原为普通列;否则,如设置为True,原索引列被会丢弃。

                inplace:输入布尔值,表示当前操作是否对原数据生效,默认为False。

        如下代码我先通过set_index() 方法将字段age列数据设置为索引,并赋值为新变量df_new,之后会使用reset_index() 方法来说明该方法的作用。

import pandas as pd
import numpy as np

# 生成模拟数据
generd = ['男', '女']
boolean = [True, False]

df = pd.DataFrame({"height": np.random.randint(150, 190, 5),
                   "weight": np.random.randint(40, 80, 5),
                   "age": np.random.randint(20, 100, 5),
                   "gender": [generd[x] for x in np.random.randint(0, len(generd), 5)],
                   "smoker": [boolean[x] for x in np.random.randint(0, 2, 5)]
                   },
                  index=list("abcde"))

print(df)
print("==============================================")
df_new = df.set_index(keys="age", drop=True)
print(df_new)

"""
#结果

   height  weight  age gender  smoker
a     187      51   88      女   False
b     174      46   74      女   False
c     189      41   42      男    True
d     160      54   48      女    True
e     180      58   34      女   False
==============================================
     height  weight gender  smoker
age                               
88      187      51      女   False
74      174      46      女   False
42      189      41      男    True
48      160      54      女    True
34      180      58      女   False

"""

        现在针对df_new对象变量使用reset_index()方法,同时设置drop=False(默认为False)代表原来的索引列age会保留并被还原为普通列,同时索引列变为默认的整型索引。

import pandas as pd
import numpy as np

# 生成模拟数据
generd = ['男', '女']
boolean = [True, False]

df = pd.DataFrame({"height": np.random.randint(150, 190, 5),
                   "weight": np.random.randint(40, 80, 5),
                   "age": np.random.randint(20, 100, 5),
                   "gender": [generd[x] for x in np.random.randint(0, len(generd), 5)],
                   "smoker": [boolean[x] for x in np.random.randint(0, 2, 5)]
                   },
                  index=list("abcde"))

print(df)
print("==============================================")
df_new = df.set_index(keys="age", drop=True)
print(df_new)
print("==============================================")
print(df_new.reset_index(drop=False))

"""
#结果

   height  weight  age gender  smoker
a     172      70   98      女   False
b     186      47   48      女   False
c     172      72   90      男   False
d     151      64   89      女   False
e     170      53   73      女    True
==============================================
     height  weight gender  smoker
age                               
98      172      70      女   False
48      186      47      女   False
90      172      72      男   False
89      151      64      女   False
73      170      53      女    True
==============================================
   age  height  weight gender  smoker
0   98     172      70      女   False
1   48     186      47      女   False
2   90     172      72      男   False
3   89     151      64      女   False
4   73     170      53      女    True

"""

        当drop=True时,除了通过reset_index()重新添加了整型索引后,age索引列已经被移除。 

import pandas as pd
import numpy as np

# 生成模拟数据
generd = ['男', '女']
boolean = [True, False]

df = pd.DataFrame({"height": np.random.randint(150, 190, 5),
                   "weight": np.random.randint(40, 80, 5),
                   "age": np.random.randint(20, 100, 5),
                   "gender": [generd[x] for x in np.random.randint(0, len(generd), 5)],
                   "smoker": [boolean[x] for x in np.random.randint(0, 2, 5)]
                   },
                  index=list("abcde"))

print(df)
print("==============================================")
df_new = df.set_index(keys="age", drop=True)
print(df_new)
print("==============================================")
print(df_new.reset_index(drop=True))

"""
#结果

   height  weight  age gender  smoker
a     157      66   70      女   False
b     178      60   30      女    True
c     175      67   83      女   False
d     169      79   39      男    True
e     157      46   79      男    True
==============================================
     height  weight gender  smoker
age                               
70      157      66      女   False
30      178      60      女    True
83      175      67      女   False
39      169      79      男    True
79      157      46      男    True
==============================================
   height  weight gender  smoker
0     157      66      女   False
1     178      60      女    True
2     175      67      女   False
3     169      79      男    True
4     157      46      男    True

"""
        reset_index() 案例场景说明

        理解了方法固然也要明白什么场景下使用,这样才能便于更好的记住。通常在做数据预处理的时候,会对数据表的缺失值或者其它不符合预期的值做移除,这个时候很容易会遇到索引    值不再连贯,那么就需要重新设置索引排序。

         如下例子我先模拟生成了一个5行5列的数据表,它的默认索引为整型索引。因为一些需求通过drop() 方法移除了索引行为2、4的数据。可以从以下代码看到处理过后的数据只剩下0,1,3  索引行数据。

import numpy as np
import pandas as pd

df = pd.DataFrame(np.random.randn(5, 5),
                  columns=['shanghai',
                           'beijing',
                           'nanjing',
                           'wuhan',
                           'guangzhou'])
print(df)
print("=============================================================")
df.drop(labels=[2, 4], inplace=True)
print(df)


"""
#结果

   shanghai   beijing   nanjing     wuhan  guangzhou
0  0.471651  2.349326 -2.462181 -0.123204  -0.650263
1  0.189930  1.498389 -1.239247  1.350404  -0.854892
2 -1.177338  0.746832 -0.119929 -0.695313  -0.776306
3  0.048976 -0.349119  0.779069  0.270240   0.019246
4 -1.013559 -0.034879  0.917059  0.270724  -0.254612
=============================================================
   shanghai   beijing   nanjing     wuhan  guangzhou
0  0.471651  2.349326 -2.462181 -0.123204  -0.650263
1  0.189930  1.498389 -1.239247  1.350404  -0.854892
3  0.048976 -0.349119  0.779069  0.270240   0.019246

"""

        因为经过处理后索引值的排序已经不连贯。为了使整形索引排序连贯,可以回忆下之前的reset_index() 方法可以重新还原整型索引。所以如下代码使用reset_index() 方法很顺利的添加了连贯的整型索引,也正因为默认参数drop=False,所以原来的索引值[0, 1, 3]被还原成了普通列,同时被系统冠名为index字段。

df = pd.DataFrame(np.random.randn(5, 5),
                  columns=['shanghai',
                           'beijing',
                           'nanjing',
                           'wuhan',
                           'guangzhou'])
print(df)
print("=============================================================")
df.drop(labels=[2, 4], inplace=True)
print(df)
print("=============================================================")
print(df.reset_index())


"""
#结果

   shanghai   beijing   nanjing     wuhan  guangzhou
0  0.471651  2.349326 -2.462181 -0.123204  -0.650263
1  0.189930  1.498389 -1.239247  1.350404  -0.854892
2 -1.177338  0.746832 -0.119929 -0.695313  -0.776306
3  0.048976 -0.349119  0.779069  0.270240   0.019246
4 -1.013559 -0.034879  0.917059  0.270724  -0.254612
=============================================================
   shanghai   beijing   nanjing     wuhan  guangzhou
0  0.471651  2.349326 -2.462181 -0.123204  -0.650263
1  0.189930  1.498389 -1.239247  1.350404  -0.854892
3  0.048976 -0.349119  0.779069  0.270240   0.019246
=============================================================
   index  shanghai   beijing   nanjing     wuhan  guangzhou
0      0  0.471651  2.349326 -2.462181 -0.123204  -0.650263
1      1  0.189930  1.498389 -1.239247  1.350404  -0.854892
2      3  0.048976 -0.349119  0.779069  0.270240   0.019246
"""

        但是通常我们会选择移除该列,所以就像以下那样可以显示设置参数drop = True 进行移除。

import numpy as np
import pandas as pd

df = pd.DataFrame(np.random.randn(5, 5),
                  columns=['shanghai',
                           'beijing',
                           'nanjing',
                           'wuhan',
                           'guangzhou'])
print(df)
print("=============================================================")
df.drop(labels=[2, 4], inplace=True)
print(df)
print("=============================================================")
print(df.reset_index())
print("=============================================================")
print(df.reset_index(drop=True))


"""
#结果

   shanghai   beijing   nanjing     wuhan  guangzhou
0  0.471651  2.349326 -2.462181 -0.123204  -0.650263
1  0.189930  1.498389 -1.239247  1.350404  -0.854892
2 -1.177338  0.746832 -0.119929 -0.695313  -0.776306
3  0.048976 -0.349119  0.779069  0.270240   0.019246
4 -1.013559 -0.034879  0.917059  0.270724  -0.254612
=============================================================
   shanghai   beijing   nanjing     wuhan  guangzhou
0  0.471651  2.349326 -2.462181 -0.123204  -0.650263
1  0.189930  1.498389 -1.239247  1.350404  -0.854892
3  0.048976 -0.349119  0.779069  0.270240   0.019246
=============================================================
   index  shanghai   beijing   nanjing     wuhan  guangzhou
0      0  0.471651  2.349326 -2.462181 -0.123204  -0.650263
1      1  0.189930  1.498389 -1.239247  1.350404  -0.854892
2      3  0.048976 -0.349119  0.779069  0.270240   0.019246
=============================================================
   shanghai   beijing   nanjing     wuhan  guangzhou
0  0.471651  2.349326 -2.462181 -0.123204  -0.650263
1  0.189930  1.498389 -1.239247  1.350404  -0.854892
2  0.048976 -0.349119  0.779069  0.270240   0.019246

"""

        但是千万别忘了,任何移除操作并不会真正修改数据对象本身,如需要一定要设置inplace参数。

import numpy as np
import pandas as pd

df = pd.DataFrame(np.random.randn(5, 5),
                  columns=['shanghai',
                           'beijing',
                           'nanjing',
                           'wuhan',
                           'guangzhou'])
print(df)
print("=============================================================")
df.drop(labels=[2, 4], inplace=True)
print(df)
print("=============================================================")
print(df.reset_index())
print("=============================================================")
print(df.reset_index(drop=True))
print("=============================================================")
print(df)#输出原df,对比是否变化
print("=============================================================")
df.reset_index(drop=True, inplace=True)
print(df)


"""
#结果

   shanghai   beijing   nanjing     wuhan  guangzhou
0  0.471651  2.349326 -2.462181 -0.123204  -0.650263
1  0.189930  1.498389 -1.239247  1.350404  -0.854892
2 -1.177338  0.746832 -0.119929 -0.695313  -0.776306
3  0.048976 -0.349119  0.779069  0.270240   0.019246
4 -1.013559 -0.034879  0.917059  0.270724  -0.254612
=============================================================
   shanghai   beijing   nanjing     wuhan  guangzhou
0  0.471651  2.349326 -2.462181 -0.123204  -0.650263
1  0.189930  1.498389 -1.239247  1.350404  -0.854892
3  0.048976 -0.349119  0.779069  0.270240   0.019246
=============================================================
   index  shanghai   beijing   nanjing     wuhan  guangzhou
0      0  0.471651  2.349326 -2.462181 -0.123204  -0.650263
1      1  0.189930  1.498389 -1.239247  1.350404  -0.854892
2      3  0.048976 -0.349119  0.779069  0.270240   0.019246
=============================================================
   shanghai   beijing   nanjing     wuhan  guangzhou
0  0.471651  2.349326 -2.462181 -0.123204  -0.650263
1  0.189930  1.498389 -1.239247  1.350404  -0.854892
2  0.048976 -0.349119  0.779069  0.270240   0.019246
=============================================================
   shanghai   beijing   nanjing     wuhan  guangzhou
0  0.471651  2.349326 -2.462181 -0.123204  -0.650263
1  0.189930  1.498389 -1.239247  1.350404  -0.854892
3  0.048976 -0.349119  0.779069  0.270240   0.019246
=============================================================
   shanghai   beijing   nanjing     wuhan  guangzhou
0  0.471651  2.349326 -2.462181 -0.123204  -0.650263
1  0.189930  1.498389 -1.239247  1.350404  -0.854892
2  0.048976 -0.349119  0.779069  0.270240   0.019246

"""

(3)reindex()

        reindex() 顾名思义它的作用是用来重定义索引的,如果定义的索引没有匹配的数据,默认将已缺失值填充。而索引可以分 “行” 索引与 “列” 索引,所以reindex自然对于两者的修改都可以胜任。它在Series和DataFrame中都非常有用:

        对于DataFrame,reindex() 可以修改行、列索引或者两个都修改。

        对于Series,reindex() 会创建一个适应新索引新对象,如果某个索引值当前不存在,就会引入缺失值。

        另外,对于以上两个数据类型都可以通过fill_value参数填充默认值,也可以通过method参数设置填充方法。而method包含几个参数可以选择:

                None (默认): 不做任何填充

                pad / ffill: 用上一行的有效数据来填充。

                backfill / bfill: 用下一行的有效数据来填充。

                nearest: 用临近行的有效数据来填充。

        Series中的reindex() 使用

                如下例子,先讲解下在Series中reindex() 方法的使用。同样,为了更好的说明,先使用Series初始创建数据,该数据默认的索引为5个字母a, b, c, d, e。

import numpy as np
import pandas as pd

obj = pd.Series(np.random.randint(low=1, high=6, size=5), index=list("abcde"))
print(obj)


"""
#结果

a    5
b    3
c    3
d    4
e    1
dtype: int32

"""

                接着,使用reindex() 方法对数据的索引进行重定义为a, b, c, d, e, f。因为f之前并不存在,是我们新定义的,所以也没有匹配的数据值,那么默认就以缺失值NaN填充。当然也可以像下面最后一段代码那样使用 fill_value 参数设定填充数值,这里我设置为0。

import numpy as np
import pandas as pd

obj = pd.Series(np.random.randint(low=1, high=6, size=5), index=list("abcde"))
print(obj)
print("==========================================================")
obj01 = obj.reindex(['a', 'b', 'c', 'd', 'e', 'f'])
print(obj01)
print("==========================================================")
obj02 = obj.reindex(['a', 'b', 'c', 'd', 'e', 'f'], fill_value=0.0)
print(obj02)


"""
#结果

a    5
b    3
c    3
d    4
e    1
dtype: int32
==========================================================
a    5.0
b    3.0
c    3.0
d    4.0
e    1.0
f    NaN
dtype: float64
==========================================================
a    5.0
b    3.0
c    3.0
d    4.0
e    1.0
f    0.0
dtype: float64

"""

                也可以使用设置method参数来填充,这里使用ffill参数值设定使用上一行的数据来作为填充数据。 

import numpy as np
import pandas as pd

obj = pd.Series(np.random.randint(low=1, high=6, size=5), index=list("abcde"))
print(obj)
print("==========================================================")
obj01 = obj.reindex(['a', 'b', 'c', 'd', 'e', 'f'])
print(obj01)
print("==========================================================")
obj02 = obj.reindex(['a', 'b', 'c', 'd', 'e', 'f'], fill_value=0.0)
print(obj02)
print("==========================================================")
obj03 = obj.reindex(['a', 'b', 'c', 'd', 'e', 'f'], method='ffill')
print(obj03)


"""
#结果

a    5
b    3
c    3
d    4
e    1
dtype: int32
==========================================================
a    5.0
b    3.0
c    3.0
d    4.0
e    1.0
f    NaN
dtype: float64
==========================================================
a    5.0
b    3.0
c    3.0
d    4.0
e    1.0
f    0.0
dtype: float64
==========================================================
a    5
b    3
c    3
d    4
e    1
f    1
dtype: int32

"""
         DataFrame中的reindex() 使用

                为了更好的说明,先使用DataFrame初始创建数据,该数据默认的索引为5个字母a, b, c, d, e。

import numpy as np
import pandas as pd

df = pd.DataFrame(np.random.randint(low=1, high=11, size=(5, 5)),
                  columns=['anders', 'mary', 'jack', 'tom', 'john'],
                  index=list('abcde'))
print(df)


"""
#结果

   anders  mary  jack  tom  john
a       4     9    10    8     1
b       6     2     3    4     9
c       1     6     8    4     7
d       9     7     3    2     1
e       8     6     4    8     5

"""

                之前提到过在DataFrame中reindex() 可以修改行、列索引。所以如下代码分别对index行索引和columns列索引进行了设置。

import numpy as np
import pandas as pd

df = pd.DataFrame(np.random.randint(low=1, high=11, size=(5, 5)),
                  columns=['anders', 'mary', 'jack', 'tom', 'john'],
                  index=list('abcde'))
print(df)
print("=================================================")
print(df.reindex(list('abcdef')))
print("=================================================")
print(df.reindex(columns=['anders', 'mary', 'jjj', 'ttt', 'ccc']))


"""
#结果

   anders  mary  jack  tom  john
a       4     9    10    8     1
b       6     2     3    4     9
c       1     6     8    4     7
d       9     7     3    2     1
e       8     6     4    8     5
=================================================
   anders  mary  jack  tom  john
a     4.0   9.0  10.0  8.0   1.0
b     6.0   2.0   3.0  4.0   9.0
c     1.0   6.0   8.0  4.0   7.0
d     9.0   7.0   3.0  2.0   1.0
e     8.0   6.0   4.0  8.0   5.0
f     NaN   NaN   NaN  NaN   NaN
=================================================
   anders  mary  jjj  ttt  ccc
a       4     9  NaN  NaN  NaN
b       6     2  NaN  NaN  NaN
c       1     6  NaN  NaN  NaN
d       9     7  NaN  NaN  NaN
e       8     6  NaN  NaN  NaN

"""

                当然也可以同时指定index和columns来重定义索引,因为定义的索引既没有匹配的数据也没设置默认填充,所以就以缺失值填充。

import numpy as np
import pandas as pd

df = pd.DataFrame(np.random.randint(low=1, high=11, size=(5, 5)),
                  columns=['anders', 'mary', 'jack', 'tom', 'john'],
                  index=list('abcde'))
print(df)
print("=================================================")
print(df.reindex(list('abcdef')))
print("=================================================")
print(df.reindex(columns=['anders', 'mary', 'jjj', 'ttt', 'ccc']))
print("=================================================")
print(df.reindex(index=list('abcdef'),
                 columns=['anders', 'mary', 'jjj', 'ttt', 'ccc']))


"""
#结果

   anders  mary  jack  tom  john
a       4     9    10    8     1
b       6     2     3    4     9
c       1     6     8    4     7
d       9     7     3    2     1
e       8     6     4    8     5
=================================================
   anders  mary  jack  tom  john
a     4.0   9.0  10.0  8.0   1.0
b     6.0   2.0   3.0  4.0   9.0
c     1.0   6.0   8.0  4.0   7.0
d     9.0   7.0   3.0  2.0   1.0
e     8.0   6.0   4.0  8.0   5.0
f     NaN   NaN   NaN  NaN   NaN
=================================================
   anders  mary  jjj  ttt  ccc
a       4     9  NaN  NaN  NaN
b       6     2  NaN  NaN  NaN
c       1     6  NaN  NaN  NaN
d       9     7  NaN  NaN  NaN
e       8     6  NaN  NaN  NaN
=================================================
   anders  mary  jjj  ttt  ccc
a     4.0   9.0  NaN  NaN  NaN
b     6.0   2.0  NaN  NaN  NaN
c     1.0   6.0  NaN  NaN  NaN
d     9.0   7.0  NaN  NaN  NaN
e     8.0   6.0  NaN  NaN  NaN
f     NaN   NaN  NaN  NaN  NaN

"""

                当然不仅可以通过重定义索引来增加新索引,反过来也可以做一些移除索引达到drop的效果。

import numpy as np
import pandas as pd

df = pd.DataFrame(np.random.randint(low=1, high=11, size=(5, 5)),
                  columns=['anders', 'mary', 'jack', 'tom', 'john'],
                  index=list('abcde'))
print(df)
print("=================================================")
print(df.reindex(index=list("abc"), columns=['anders', 'mary']))


"""
#结果

   anders  mary  jack  tom  john
a       4     9    10    8     1
b       6     2     3    4     9
c       1     6     8    4     7
d       9     7     3    2     1
e       8     6     4    8     5
=================================================
   anders  mary
a       4     9
b       6     2
c       1     6

"""

                可以看到如在Series中操作reindex() 一样,因为重定义的索引没有找到匹配的对象数据,所以默认填充为缺失值。而在DataFrame中依然可以使用fill_value与method两个参数方法来设定默认填充值。

import numpy as np
import pandas as pd

df = pd.DataFrame(np.random.randint(low=1, high=11, size=(5, 5)),
                  columns=['anders', 'mary', 'jack', 'tom', 'john'],
                  index=list('abcde'))
print(df)
print("=================================================")
print(df.reindex(list('abcdef'), fill_value=100))
print("=================================================")
print(df.reindex(list('abcdef'), method='ffill'))


"""
#结果

   anders  mary  jack  tom  john
a       4     9    10    8     1
b       6     2     3    4     9
c       1     6     8    4     7
d       9     7     3    2     1
e       8     6     4    8     5
=================================================
   anders  mary  jack  tom  john
a       4     9    10    8     1
b       6     2     3    4     9
c       1     6     8    4     7
d       9     7     3    2     1
e       8     6     4    8     5
f     100   100   100  100   100
=================================================
   anders  mary  jack  tom  john
a       4     9    10    8     1
b       6     2     3    4     9
c       1     6     8    4     7
d       9     7     3    2     1
e       8     6     4    8     5
f       8     6     4    8     5

"""

                method参数只适用于index是单调递增或者单调递减的情形。同时引用一张网络图很好的说明了method参数的使用逻辑。 

                

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值