pandas(六) -- 合并、连接、去重、替换

  1. pd.merge()
pd.merge(left, right, how='inner', on=None, left_on=None, right_on=None,left_index=False, right_index=False, sort=True,suffixes=('x', 'y'), copy=True, indicator=False)

参数

left : DataFrame对象
right : DataFrame 或有名字的 Series 对象
how : 合并方式:{'left', 'right', 'outer', 'inner'},默认是'inner',取交集
        * left/ right: 使用left/right的键连接
        * outer: 使用left和right的键,取并集
        * inner: 使用left和right相同的键,取交集
on : label or list.(列名或者index的名称,用来连接两个表的)  
left_on/right_on : label or list, or array-like(left/right 列名或者index的名称)        
left_index/right_index  : bool, default False(是否使用left/right的index作为连接的键值。)
sort : bool, default False.如果为真,对键值排序,否则,键值顺序取决于连接方式。
suffixes : tuple of (str, str), default ('_x', '_y')left和right重复的列名添加后缀名,以示区分。
copy : bool, default True. If False, avoid copy if possible.
indicator : bool or str, default False
validate : str, optional    

1.1 on

**********  df1  **********
    A   B key
0  A0  B0  K0
1  A1  B1  K1
2  A2  B2  K2
3  A3  B3  K3
**********  df2  **********
    C   D key
0  C0  D0  K0
1  C1  D1  K1
2  C2  D2  K2
3  C3  D3  K3
pd.merge(df1, df2, on='key')

通过df1和df2共同关键字‘key’,取交集

**********  merge  **********
    A   B key   C   D
0  A0  B0  K0  C0  D0
1  A1  B1  K1  C1  D1
2  A2  B2  K2  C2  D2
3  A3  B3  K3  C3  D3
  • 多个关键字的情况
pd.merge(df3, df4, on=['key1','key2'])

通过df3, df4关键字’key1’,'key2’取相同值时合并。

**********  df3  **********
    A   B key1 key2
0  A0  B0   K0   K0
1  A1  B1   K0   K1
2  A2  B2   K1   K0
3  A3  B3   K2   K1
**********  df4  **********
    C   D key1 key2
0  C0  D0   K0   K0
1  C1  D1   K1   K0
2  C2  D2   K1   K0
3  C3  D3   K2   K0
    A   B key1 key2   C   D
0  A0  B0   K0   K0  C0  D0
1  A2  B2   K1   K0  C1  D1
2  A2  B2   K1   K0  C2  D2
  • how = 'outer' 根据df3和df4所有关键字合并
    print(pd.merge(df3, df4, on=['key1','key2'], how = 'outer'))
    没有响应键值的取NaN
     A    B key1 key2    C    D
0   A0   B0   K0   K0   C0   D0
1   A1   B1   K0   K1  NaN  NaN
2   A2   B2   K1   K0   C1   D1
3   A2   B2   K1   K0   C2   D2
4   A3   B3   K2   K1  NaN  NaN
5  NaN  NaN   K2   K0   C3   D3
  • how = 'left' 根据df3的关键字合并。how = 'right' 是相似的
print(pd.merge(df3, df4, on=['key1','key2'], how = 'left')) 
  A   B key1 key2    C    D
0  A0  B0   K0   K0   C0   D0
1  A1  B1   K0   K1  NaN  NaN
2  A2  B2   K1   K0   C1   D1
3  A2  B2   K1   K0   C2   D2
4  A3  B3   K2   K1  NaN  NaN

当left和right没有相同的关键字时,使用参数 left_on, right_on, left_index, right_index 来连接。
left_on/ right_on : 类型 label or list left/right or array-like。 使用的关键字是什么
left_index, right_index : 类型 bool。是否使用left/right的index作为关键字。
{ left_on, right_on} 和 { left_index, right_index}一起共有四种组合方式。
介绍两种:

  • left_on和right_on。df1, df2分别以关键字‘lkey’和‘rkey’连接
**********  df1  **********
  data1 lkey
0      0    b
1      1    b
2      2    a
3      3    c
4      4    a
5      5    a
6      6    b
**********  df2  **********
  date2 rkey
0      0    a
1      1    b
2      2    d
pd.merge(df1, df2, left_on='lkey', right_on='rkey')
   data1 lkey  date2 rkey
0      0    b      1    b
1      1    b      1    b
2      6    b      1    b
3      2    a      0    a
4      4    a      0    a
5      5    a      0    a
  • left_on和right_index。df1, df2分别以关键字‘lkey’和index连接。合并的关键字以left的列名作为关键字
**********  df1  **********
   data1 key
0      0   a
1      1   b
2      2   c
3      3   d
4      4   f
5      5   e
6      6   g
**********  df2  **********
   date2
a    100
b    101
c    102
d    103
e    104
pd.merge(df1, df2, left_on='key', right_index=True)
   data1 key  date2
0      0   a    100
1      1   b    101
2      2   c    102
3      3   d    103
5      5   e    104
  1. pd.concate()
    根据指定的axis连接pandas对象。默认连接方式是’outer’.
pd.concat(objs, axis=0, join='outer', join_axes=None, ignore_index=False,keys=None, levels=None, names=None, verify_integrity=False,copy=True)
Parameters
----------
objs : a sequence or mapping of Series, DataFrame, or Panel objects。只有一个变量。
axis : {0/'index', 1/'columns'}, default 0
join : {'inner', 'outer'}, default 'outer'  How to handle indexes on other axis(es)
join_axes : list of Index objects   Specific indexes to use for the other n - 1 axes instead of performing
    inner/outer set logic
ignore_index : boolean, default False。如果为真,使用0,1,...,n-1作为新的索引

keys : sequence, default None
    If multiple levels passed, should contain tuples. Construct
    hierarchical index using the passed keys as the outermost level
levels : list of sequences, default None
    Specific levels (unique values) to use for constructing a
    MultiIndex. Otherwise they will be inferred from the keys
names : list, default None
verify_integrity : boolean, default False。检测是否有重复的axis
sort : boolean, default None
   .. versionadded:: 0.23.0
copy : boolean, default True   If False, do not copy data unnecessarily
  • 默认参数(axis = 0,垂直向下连接)
s1 = pd.Series([1,2,3])
s2 = pd.Series([2,3,4])
print(pd.concat([s1,s2]))

0    1
1    2
2    3
0    2
1    3
2    4
  1. .replace()
    可一次性替换一个值或多个值。 可传入列表或字典
s = pd.Series(list('ascaazsd'))
print(s.replace('a', np.nan))#替换单个值
print(s.replace(['a','s'] ,np.nan))#多个值替换成同一值
print(s.replace({'a':'hello world!','s':123}))#多个值替换成不同值,用字典传入
**********  'a', np.nan  **********
0    NaN
1      s
2      c
3    NaN
4    NaN
5      z
6      s
7      d
dtype: object
**********  ['a','s'] ,np.nan  **********
0    NaN
1    NaN
2      c
3    NaN
4    NaN
5      z
6    NaN
7      d
dtype: object
**********  {'a':'hello world!','s':123}  **********
0    hello world!
1             123
2               c
3    hello world!
4    hello world!
5               z
6             123
7               d
dtype: object
  1. .duplicated()
s = pd.Series([1,1,1,1,2,2,2,3,4,5,5,5,5])
print(s.duplicated())
0     False
1      True
2      True
3      True
4     False
5      True
6      True
7     False
8     False
9     False
10     True
11     True
12     True
print(s[s.duplicated() == False])#s中的唯一项。效果与.unique()相似
0    1
4    2
7    3
8    4
9    5
dtype: int64

s_re = s.drop_duplicates()# 去掉重复项。效果与.unique()相似

0    1
4    2
7    3
8    4
9    5
dtype: int64
  • 1
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值