Series第四讲 重新索引、选择、标签 操作(上)

2020-09-17  本文已影响0人  butters001

Series第四讲 重新索引、选择、标签 操作 (上)

由于第四讲涉及方法较多,此处分为上下两节各讲一部分。防止🧠混乱

重新索引、选择、标签方法总览(上)

详细介绍

先来创建一个Series

In [2]: s = pd.Series([1, 2, 3, 4, None], index=['a', 'b', 'c', 'd', 'e'])      

In [3]: s                                                                       
Out[3]: 
a    1.0
b    2.0
c    3.0
d    4.0
e    NaN
dtype: float64
  1. Series.align(other, join='outer', axis=None, level=None, copy=True, fill_value=None, method=None, limit=None, fill_axis=0, broadcast_axis=None)

使用指定的join方法将两个对象在其轴上对齐

参数介绍:

例子一

# 先创建两个df
df1 = pd.DataFrame([[1,2,3,4], [6,7,8,9]], columns=['D', 'B', 'E', 'A'], index=[1,2])
df2 = pd.DataFrame([[10,20,30,40], [60,70,80,90], [600,700,800,900]], columns=['A', 'B', 'C', 'D'], index=[2,3,4])

In [55]: df1                                                                    
Out[55]: 
   D  B  E  A
1  1  2  3  4
2  6  7  8  9

In [56]: df2                                                                    
Out[56]: 
     A    B    C    D
2   10   20   30   40
3   60   70   80   90
4  600  700  800  900

# 让我们对齐这两个df,按列对齐(axis=1),并对列标签执行外连接(join='outer')
# 每个df将包含全部列,行标签用各自的
a1, a2 = df1.align(df2, join='outer', axis=1)

In [58]: a1                                                                     
Out[58]: 
   A  B   C  D  E
1  4  2 NaN  1  3
2  9  7 NaN  6  8

In [59]: a2                                                                     
Out[59]: 
     A    B    C    D   E
2   10   20   30   40 NaN
3   60   70   80   90 NaN
4  600  700  800  900 NaN

这里有几点需要注意:

例子二

# 行和列上都对齐,且右连接
In [60]: a1, a2 = df1.align(df2, join='right', axis=None)                       
In [61]: a1                                                                     
Out[61]: 
     A    B   C    D
2  9.0  7.0 NaN  6.0
3  NaN  NaN NaN  NaN
4  NaN  NaN NaN  NaN

In [62]: a2                                                                     
Out[62]: 
     A    B    C    D
2   10   20   30   40
3   60   70   80   90
4  600  700  800  900

例子三

# 内连接 且列对齐
In [63]: a1, a2 = df1.align(df2, join='inner', axis=1)                          

In [64]: a1                                                                     
Out[64]: 
   D  B  A
1  1  2  4
2  6  7  9

In [65]: a2                                                                     
Out[65]: 
     D    B    A
2   40   20   10
3   90   70   60
4  900  700  600

总之,如果要确保两个数据帧之间的行和/或列排列相同,而不更改两个df中包含的任何数据,请使用DataFrame.align() 或 Series.align()

align 例子说明借鉴此处

  1. Series.drop(labels=None, axis=0, index=None, columns=None, level=None, inplace=False, errors='raise')

根据指定索引删除行/列

主要参数说明:

In [4]: s.drop('a')                                                             
Out[4]: 
b    2.0
c    3.0
d    4.0
e    NaN
dtype: float64

# 指定error参数则不抛出异常
In [5]: s.drop(['f','a','b'], errors='ignore')                                  
Out[5]: 
c    3.0
d    4.0
e    NaN
dtype: float64

# 多层索引时 变量mu_s参考droplevel里定义的对象
In [72]: mu_s.drop('a',level='level1')                                          
Out[72]: 
level1  level2  level3
b       1       <          6
                >          7
        2       <          8
                >          9
        3       <         10
                >         11
dtype: int64

In [73]: mu_s.drop('a',level=0)                                                 
Out[73]: 
level1  level2  level3
b       1       <          6
                >          7
        2       <          8
                >          9
        3       <         10
                >         11
dtype: int64
  1. Series.droplevel(level, axis=0)

多级索引时,删除指定层级的索引

参数说明:

# 先创建一个多级索引的Series
# 1 创建多级索引
In [27]: mu_index=pd.MultiIndex.from_product([['a','b'],['1','2','3'],['<', '>']
    ...: ], names=['level1', 'level2', 'level3']) 

# 2 创建Series
In [28]: mu_s = pd.Series(range(12), index=mu_index)                            
In [29]: mu_s                                                                   
Out[29]: 
level1  level2  level3
a       1       <          0
                >          1
        2       <          2
                >          3
        3       <          4
                >          5
b       1       <          6
                >          7
        2       <          8
                >          9
        3       <         10
                >         11
dtype: int64

# 删除指定level级的索引
In [30]: mu_s.droplevel([0,1])                                                  
Out[30]: 
level3
<     0
>     1
<     2
>     3
<     4
>     5
<     6
>     7
<     8
>     9
<    10
>    11
dtype: int64

In [33]: mu_s.droplevel([0, 'level3'])                                          
Out[33]: 
level2
1     0
1     1
2     2
2     3
3     4
3     5
1     6
1     7
2     8
2     9
3    10
3    11
dtype: int64

  1. Series.drop_duplicates(keep='first', inplace=False)

返回删除了重复值的Series

参数说明:

In [35]: s = pd.Series(['lama', 'cow', 'lama', 'beetle', 'lama', 'hippo'], 
    ...:               name='animal')                                           

In [36]: s                                                                      
Out[36]: 
0      lama
1       cow
2      lama
3    beetle
4      lama
5     hippo
Name: animal, dtype: object

# 默认只保留第一次出现的重复项
In [38]: s.drop_duplicates()                                                    
Out[38]: 
0      lama
1       cow
3    beetle
5     hippo
Name: animal, dtype: object

# “last”只保留最后一次出现的重复项
In [37]: s.drop_duplicates(keep='last')                                         
Out[37]: 
1       cow
3    beetle
4      lama
5     hippo
Name: animal, dtype: object
  1. Series.duplicated(keep='first')

重复值为True,其他为False

参数说明:

animals = pd.Series(['lama', 'cow', 'lama', 'beetle', 'lama'])
animals.duplicated()
0    False
1    False
2     True
3    False
4     True
dtype: bool

animals.duplicated(keep='first')
0    False
1    False
2     True
3    False
4     True
dtype: bool

animals.duplicated(keep='last')
0     True
1    False
2     True
3    False
4    False
dtype: bool

animals.duplicated(keep=False)
0     True
1    False
2     True
3    False
4     True
dtype: bool

  1. Series.equals(other)

两个对象是否包含相同的元素,比较它们是否具有相同的形状和元素,相同位置的NaN被认为是相等的

labels的类型不同 元素类型和值相同是 返回True

labels的类型相同 元素的值相同但类型不同时 返回False

df = pd.DataFrame({1: [10], 2: [20]})
df
    1   2
0  10  20

# 元素和列标签具有相同的类型和值,它们将返回True
exactly_equal = pd.DataFrame({1: [10], 2: [20]})
exactly_equal
    1   2
0  10  20
df.equals(exactly_equal)
True

# 具有相同的元素类型和值,但是列标签具有不同的类型,它们仍将返回True
different_column_type = pd.DataFrame({1.0: [10], 2.0: [20]})
different_column_type
   1.0  2.0
0   10   20
df.equals(different_column_type)
True

# 其元素的相同值具有不同的类型,即使它们的列标签具有相同的值和类型,它们也将返回False
different_data_type = pd.DataFrame({1: [10.0], 2: [20.0]})
different_data_type
      1     2
0  10.0  20.0
df.equals(different_data_type)
False
  1. Series.first(offset)

根据日期偏移量选择时间序列数据的初始时段

参数说明:

# 创建Series
i = pd.date_range('2018-04-09', periods=4, freq='2D')
ts = pd.DataFrame({'A': [1, 2, 3, 4]}, index=i)
ts
            A
2018-04-09  1
2018-04-11  2
2018-04-13  3
2018-04-15  4

# 获取前3天的行:
ts.first('3D')
            A
2018-04-09  1
2018-04-11  2
  1. Series.last(offset)

选择后几天的数据

  1. Series.head(n=5)

获取Series的前n行数据

In [75]: s.head(2)                                                              
Out[75]: 
a    1.0
b    2.0
dtype: float64
  1. Series.tail(n=5)

获取Series的后n行数据

  1. Series.idxmax(axis=0, skipna=True, *args, **kwargs)

最大值的label标签

参数说明:

In [47]: s.idxmax()                                                             
Out[47]: 'd'

In [49]: s.idxmax(skipna=False)                                                 
Out[49]: nan
  1. Series.idxmin(axis=0, skipna=True, *args, **kwargs)

最小值的label标签

In [46]: s.idxmin()                                                             
Out[46]: 'a'
  1. Series.isin(values)

返回bool列表,表示每一个元素是否在values(元组或列表)里

In [50]: s.isin([None])                                                         
Out[50]: 
a    False
b    False
c    False
d    False
e     True
dtype: bool

In [53]: s.isin([1, 2])                                                         
Out[53]: 
a     True
b     True
c    False
d    False
e    False
dtype: bool
上一篇 下一篇

猜你喜欢

热点阅读