Pandas-04(缺失数据、分组、合并连接、级联)

1.缺失数据

1.1 isnull()和notnull()检测缺失数据

1.2 fillna()填充缺失值

1.3 删除NaN的行

1.4 replace()替换丢失的值或者通用值

2. 分组

2.1 groupby()分组

2.2 get_group()选择组

3.合并连接merge()

3.1 示例

3.2 merge()合并

3.3 合并模式

4.级联concat()

由于数据有多种形式和形式,pandas 旨在灵活处理缺失数据。虽然 NaN出于计算速度和方便的原因,它是默认的缺失值标记,但我们需要能够使用不同类型的数据轻松检测该值:浮点、整数、布尔值和一般对象。然而,在许多情况下,Python None会出现,我们也希望考虑”缺失”或”不可用”或”NA”。

1.1 isnull()和notnull()检测缺失数据

为了更容易检测缺失值(以及跨不同的数组 dtype),pandas 提供了isnull()和notnull()函数,它们也是 Series 和 DataFrame 对象的方法:

1. isnull()

示例:

import pandas as pd
import numpy as np

df = pd.DataFrame(np.random.randn(5,3),index=['a','c','e','f','h'],columns=['one','two','three'])
df = df.reindex(['a','b','c','d','e','f','h'])

df

输出结果:
         one        two       three
a   -0.864969   0.299120    -0.936382
b        NaN         NaN         NaN
c   1.573142    -2.359139   0.118325
d        NaN         NaN         NaN
e   1.070140    -0.392129   -0.647714
f   -0.886120   -0.926900   1.170801
h   0.725739    1.182897    -0.899262
#检查缺失数据
df[df['one'].isnull()]

输出结果:
    one  two    three
b   NaN  NaN    NaN
d   NaN  NaN    NaN

2. notnull()

#检查是不是非空的
df['one'].notnull()

输出结果:
a     True
b    False
c     True
d    False
e     True
f     True
h     True
Name: one, dtype: bool

输出非空结果:

df[df['one'].notnull()]

输出结果:
          one       two      three
a   -0.864969   0.299120    -0.936382
c   1.573142    -2.359139   0.118325
e   1.070140    -0.392129   -0.647714
f   -0.886120   -0.926900   1.170801
h   0.725739    1.182897    -0.899262

1.2 fillna()填充缺失值

finall()可以通过几种方式用非 NA 数据”填充”NA 值。

1.将NA值替换为标量值

指定列内容[colomns]填充content:

df["colomns"].fillna("content")

2.向前或向后填补空白

可以指定method的方法pad向前填充值或使用bfill向后填充值:

df.fillna(method="pad")

3. 限制填充量

当只想连续填充一定数量的数据点,可以使用limit关键字:

df.fillna(method="pad", limit=1)

4.示例:

 #  df数据
       one         two         three
a   -0.864969   0.299120    -0.936382
b   NaN NaN NaN
c   1.573142    -2.359139   0.118325
d   NaN NaN NaN
e   1.070140    -0.392129   -0.647714
f   -0.886120   -0.926900   1.170801
h   0.725739    1.182897    -0.899262
#可以填充我们想要的数据
df.fillna(df.mean())

#输出结果:
one two three
a   -0.864969   0.299120    -0.936382
b   0.323586    -0.439230   -0.238846
c   1.573142    -2.359139   0.118325
d   0.323586    -0.439230   -0.238846
e   1.070140    -0.392129   -0.647714
f   -0.886120   -0.926900   1.170801
h   0.725739    1.182897    -0.899262

#将前面的数据填充进来
df.fillna(method='pad')

#输出结果:
one two three
a   -0.864969   0.299120    -0.936382
b   -0.864969   0.299120    -0.936382
c   1.573142    -2.359139   0.118325
d   1.573142    -2.359139   0.118325
e   1.070140    -0.392129   -0.647714
f   -0.886120   -0.926900   1.170801
h   0.725739    1.182897    -0.899262

#将后面的数据填充进来
df.fillna(method='backfill')

#输出结果 :
one two three
a   -0.864969   0.299120    -0.936382
b   1.573142    -2.359139   0.118325
c   1.573142    -2.359139   0.118325
d   1.070140    -0.392129   -0.647714
e   1.070140    -0.392129   -0.647714
f   -0.886120   -0.926900   1.170801
h   0.725739    1.182897    -0.899262

1.3 删除NaN的行

df.dropna() #删除有NAN的行

示例:

#删除有NAN的行
df.dropna()

#输出结果:
one two three
a   -0.864969   0.299120    -0.936382
c   1.573142    -2.359139   0.118325
e   1.070140    -0.392129   -0.647714
f   -0.886120   -0.926900   1.170801
h   0.725739    1.182897    -0.899262

1.4 replace()替换丢失的值或者通用值

replace({nan:替换值})

示例:

df.replace({np.nan:10})

输出结果:
       one         two        three
a   -0.864969   0.299120    -0.936382
b   10.000000   10.000000   10.000000
c   1.573142    -2.359139   0.118325
d   10.000000   10.000000   10.000000
e   1.070140    -0.392129   -0.647714
f   -0.886120   -0.926900   1.170801
h   0.725739    1.182897    -0.899262

df['four']=pd.Series([1,2,3,4,5,6,7],index=['a','b','c','d','e','f','h'])
df
#输出结果:
        one        two         three    four
a   -0.864969   0.299120    -0.936382    1
b        NaN          NaN         NaN    2
c   1.573142    -2.359139   0.118325     3
d        NaN          NaN         NaN    4
e   1.070140    -0.392129   -0.647714    5
f   -0.886120   -0.926900   1.170801     6
h   0.725739    1.182897    -0.899262    7

#替换NaN为10,5为1000
df.replace({np.nan:10,5:1000})

#输出结果:
         one         two       three    four
a   -0.864969   0.299120    -0.936382   1
b   10.000000   10.000000   10.000000   2
c   1.573142    -2.359139   0.118325    3
d   10.000000   10.000000   10.000000   4
e   1.070140    -0.392129   -0.647714   1000
f   -0.886120   -0.926900   1.170801    6
h   0.725739    1.182897    -0.899262   7

pandas 对象可以在它们的任何轴上分割。分组的抽象定义是提供标签到组名的映射。

“分组依据”是指涉及以下一个或多个步骤的过程:

  • 根据某些标准将数据分组。
  • 独立地对每个组 应用一个函数。
  • 结果组合成一个数据结构。

其中,拆分步骤是最直接的。事实上,在许多情况下,我们可能希望将数据集分成组,并对这些组做一些事情。

2.1 groupby()分组

示例:

import pandas as pd
import numpy as np

df = pd.DataFrame({
    'user':['小明',"小黑",'小黄','小李'],
    'gender':['男','女','女','男'],
    'score':[99,95,70,88]
})

df

#输出结果:
    user    gender  score
0   小明     男         99
1   小黑     女         95
2   小黄     女         70
3   小李     男         88

1.进行分组

#分组对象
df.groupby('gender')

#输出结果:
<pandas.core.groupby.groupby.dataframegroupby object at 0x000001fa94c1a400></pandas.core.groupby.groupby.dataframegroupby>

2.获取分组情况

df.groupby('gender').groups#&#x83B7;&#x53D6;&#x5206;&#x7EC4;&#x60C5;&#x51B5;

#&#x8F93;&#x51FA;&#x7ED3;&#x679C;&#xFF1A;
{'&#x5973;': Int64Index([1, 2], dtype='int64'),
 '&#x7537;': Int64Index([0, 3], dtype='int64')}
  1. 循环迭代组
#&#x5FAA;&#x73AF;&#x8FED;&#x4EE3;&#x7EC4;
grouped = df.groupby('gender')
for name,group in grouped:
    print(name)
    print(group)

#&#x8F93;&#x51FA;&#x7ED3;&#x679C;&#xFF1A;
 &#x5973;
     user gender  score
1   &#x5C0F;&#x9ED1;      &#x5973;     95
2   &#x5C0F;&#x9EC4;      &#x5973;     70
 &#x7537;
     user gender  score
0   &#x5C0F;&#x660E;      &#x7537;     99
3   &#x5C0F;&#x674E;      &#x7537;     88

2.2 get_group()选择组

1. get_group()基础使用

#&#x9009;&#x62E9;&#x7EC4;
grouped.get_group('&#x7537;')

#&#x8F93;&#x51FA;&#x7ED3;&#x679C;&#xFF1A;
    user    gender  score
0   &#x5C0F;&#x660E;      &#x7537;     99
3   &#x5C0F;&#x674E;      &#x7537;     88

#&#x9009;&#x62E9;&#x7EC4;&#xFF0C;&#x805A;&#x5408;&#x8BA1;&#x7B97;
grouped.get_group('&#x7537;')['score'].agg(np.mean)
grouped.get_group('&#x5973;')['score'].agg(np.max)

#&#x8F93;&#x51FA;&#x7ED3;&#x679C;&#xFF1A;
93.5
95

#&#x83B7;&#x53D6;&#x5206;&#x7EC4;&#x91CC;&#x7684;&#x957F;&#x5EA6;&#xFF08;&#xFF09;
grouped.get_group('&#x5973;').agg(np.size)

#&#x8F93;&#x51FA;&#x7ED3;&#x679C;&#xFF1A;
user      2
gender    2
score     2
dtype: int64

2.分组聚合

df['star'] = pd.Series([5,7,4,3])
df

#&#x8F93;&#x51FA;&#x7ED3;&#x679C;&#xFF1A;
    user    gender  score   star
0   &#x5C0F;&#x660E;      &#x7537;    99     5
1   &#x5C0F;&#x9ED1;      &#x5973;    95     7
2   &#x5C0F;&#x9EC4;      &#x5973;    70     4
3   &#x5C0F;&#x674E;      &#x7537;    88     3

grouped = df.groupby('gender')
#&#x6C42;&#x7537;&#x5973;&#x5E73;&#x5747;&#x5206;&#x53CA;&#x661F;&#x6570;&#x603B;&#x548C;
grouped[['score','star']].agg({'score':np.mean,'star':np.sum})

#&#x8F93;&#x51FA;&#x7ED3;&#x679C;&#xFF1A;
        score   star
gender
&#x5973;        82.5    11
&#x7537;        93.5    8

#&#x5206;&#x7EC4;&#x4E2D;&#x5E73;&#x5747;&#x5206;&#x5927;&#x4E8E;90&#x7684;
df.groupby('gender').filter(lambda x:x['score'].mean()>90)

#&#x8F93;&#x51FA;&#x7ED3;&#x679C;&#xFF1A;
    user    gender  score   star
0   &#x5C0F;&#x660E;       &#x7537;   99    5
3   &#x5C0F;&#x674E;      &#x7537;    88    3

在pandas中,可以使用merge()对多个数据进行合并,基础语法如下:

pd.merge(df1,df2...,on='&#x5408;&#x5E76;&#x7D22;&#x5F15;&#x503C;')

3.1 示例

import pandas as pd
import numpy as np

yuwen = pd.DataFrame({
    'id':[1,2,3,4,5,7],
    'name':["&#x5C0F;&#x660E;","&#x5C0F;&#x654F;","&#x5C0F;&#x7EA2;","&#x5C0F;&#x9ED1;","&#x5C0F;&#x738B;",'&#x8001;&#x9648;'],
    'yuwenScore':[98,77,45,87,66,99]

})

shuxue = pd.DataFrame({
    'id':[1,2,3,4,5,6],
    'name':["&#x5C0F;&#x660E;","&#x5C0F;&#x654F;","&#x5C0F;&#x7EA2;","&#x5C0F;&#x9ED1;","&#x5C0F;&#x738B;","&#x8001;&#x674E;"],
    'shuxueScore':[79,56,88,92,68,88]

})

 &#x8F93;&#x51FA;&#x7ED3;&#x679C;
    id  name    yuwenScore
0   1   &#x5C0F;&#x660E;    98
1   2   &#x5C0F;&#x654F;    77
2   3   &#x5C0F;&#x7EA2;    45
3   4   &#x5C0F;&#x9ED1;    87
4   5   &#x5C0F;&#x738B;    66
5   7   &#x8001;&#x9648;    99

    id  name    shuxueScore
0   1   &#x5C0F;&#x660E;    79
1   2   &#x5C0F;&#x654F;    56
2   3   &#x5C0F;&#x7EA2;    88
3   4   &#x5C0F;&#x9ED1;    92
4   5   &#x5C0F;&#x738B;    68
5   6   &#x8001;&#x674E;    88

3.2 merge()合并

pd.merge(yuwen,shuxue,on='id')#&#x901A;&#x8FC7;id&#x8FD9;&#x4E2A;&#x5065;&#x5408;&#x5E76;

#&#x8F93;&#x51FA;&#x7ED3;&#x679C;&#xFF1A;
   id   name_x  yuwenScore  name_y  shuxueScore
0   1   &#x5C0F;&#x660E;    98          &#x5C0F;&#x660E;    79
1   2   &#x5C0F;&#x654F;    77          &#x5C0F;&#x654F;    56
2   3   &#x5C0F;&#x7EA2;    45          &#x5C0F;&#x7EA2;    88
3   4   &#x5C0F;&#x9ED1;    87          &#x5C0F;&#x9ED1;    92
4   5   &#x5C0F;&#x738B;    66          &#x5C0F;&#x738B;    68

pd.merge(yuwen,shuxue,on=['id','name'])
&#x8F93;&#x51FA;&#x7ED3;&#x679C;&#xFF1A;
    id  name    yuwenScore  shuxueScore
0   1   &#x5C0F;&#x660E;        98         79
1   2   &#x5C0F;&#x654F;        77         56
2   3   &#x5C0F;&#x7EA2;        45         88
3   4   &#x5C0F;&#x9ED1;        87         92
4   5   &#x5C0F;&#x738B;        66         68

3. 3 合并模式

merge()提供how设置合并的方式,inner为键的交集,left为使用左边的键,right为使用右边的键,ourter健的联合。

示例:

#&#x9ED8;&#x8BA4;&#x662F;inner&#x5408;&#x5E76;&#x6A21;&#x5F0F;
pd.merge(yuwen,shuxue,on=['id','name'],how='inner')
&#x8F93;&#x51FA;&#x7ED3;&#x679C;
    id  name    yuwenScore  shuxueScore
0   1   &#x5C0F;&#x660E;    98          79
1   2   &#x5C0F;&#x654F;    77          56
2   3   &#x5C0F;&#x7EA2;    45          88
3   4   &#x5C0F;&#x9ED1;    87          92
4   5   &#x5C0F;&#x738B;    66          68
&#x200B;

pd.merge(yuwen,shuxue,on=['id','name'],how='right')
#&#x8F93;&#x51FA;&#x7ED3;&#x679C;
    id  name    yuwenScore  shuxueScore
0   1   &#x5C0F;&#x660E;    98.0        79
1   2   &#x5C0F;&#x654F;    77.0        56
2   3   &#x5C0F;&#x7EA2;    45.0        88
3   4   &#x5C0F;&#x9ED1;    87.0        92
4   5   &#x5C0F;&#x738B;    66.0        68
5   6   &#x8001;&#x674E;    NaN         88

pd.merge(yuwen,shuxue,on=['id','name'],how='outer')
#&#x8F93;&#x51FA;&#x7ED3;&#x679C;
    id  name    yuwenScore  shuxueScore
0   1   &#x5C0F;&#x660E;    98.0        79.0
1   2   &#x5C0F;&#x654F;    77.0        56.0
2   3   &#x5C0F;&#x7EA2;    45.0        88.0
3   4   &#x5C0F;&#x9ED1;    87.0        92.0
4   5   &#x5C0F;&#x738B;    66.0        68.0
5   7   &#x8001;&#x9648;    99.0        NaN
6   6   &#x8001;&#x674E;    NaN         88.0

pd.merge(yuwen,shuxue,on=['id','name'],how='left')
#&#x8F93;&#x51FA;&#x7ED3;&#x679C;
    id  name    yuwenScore  shuxueScore
0   1   &#x5C0F;&#x660E;    98          79.0
1   2   &#x5C0F;&#x654F;    77          56.0
2   3   &#x5C0F;&#x7EA2;    45          88.0
3   4   &#x5C0F;&#x9ED1;    87          92.0
4   5   &#x5C0F;&#x738B;    66          68.0
5   7   &#x8001;&#x9648;    99          NaN

基础语法:

pd.concat(
    objs,
    axis=0,
    join="outer",
    ignore_index=False,
    keys=None,
    levels=None,
    names=None,
    verify_integrity=False,
    copy=True,
)
  • objs: Series 或 DataFrame 对象的序列或映射。如果传递了 dict,则排序后的键将用作 keys参数,除非传递,在这种情况下将选择值(见下文)。任何 None 对象都将被静默删除,除非它们都是 None 在这种情况下将引发 ValueError 。
  • axis: {0, 1, …},默认 0。要连接的轴。
  • join: {‘inner’, ‘outer’},默认为’outer’。如何处理其他轴上的索引。外部用于联合,内部用于交叉。
  • ignore_index:布尔值,默认为 False。如果为 True,则不要使用连接轴上的索引值。结果轴将标记为 0, …, n – 1。如果您要连接对象,而连接轴没有有意义的索引信息,这将非常有用。请注意,连接中仍然尊重其他轴上的索引值。
  • keys:序列,默认无。使用传递的键作为最外层构建层次索引。如果通过了多个级别,则应包含元组。
  • levels:序列列表,默认无。用于构造 MultiIndex 的特定级别(唯一值)。否则,它们将从密钥中推断出来。
  • names:列表,默认无。生成的分层索引中的级别名称。
  • verify_integrity:布尔值,默认为 False。检查新的连接轴是否包含重复项。相对于实际的数据连接,这可能非常昂贵。
  • copy:布尔值,默认为真。如果为 False,则不要不必要地复制数据。

示例:

import numpy as np
import pandas as pd

one = pd.DataFrame({
    'name':["alex",'xm','xh','lc','ll'],
    'subject':['python','java','go','js','html'],
    'socre':[88,79,68,96,66]
})
two = pd.DataFrame({
    'name':["xc",'xm','xh','lc','ll'],
    'subject':['php','java','go','js','html'],
    'socre':[89,79,68,96,66]
})

&#x8F93;&#x51FA;&#x7ED3;&#x679C;
    name    subject socre
0   alex    python  88
1   xm      java    79
2   xh      go      68
3   lc      js      96
4   ll      html    66

    name    subject socre
0   xc        php   89
1   xm       java   79
2   xh        go    68
3   lc        js    96
4   ll       html   66

忽视索引值合并:

pd.concat([one,two],ignore_index=True)

&#x8F93;&#x51FA;&#x7ED3;&#x679C;
    name    subject socre
0   alex    python  88
1   xm      java    79
2   xh        go    68
3   lc        js    96
4   ll       html   66
5   xc       php    89
6   xm       java   79
7   xh        go    68
8   lc        js    96
9   ll       html   66

按照列进行合并

#&#x6309;&#x7167;&#x5217;&#x8FDB;&#x884C;&#x5408;&#x5E76;
pd.concat([one,two],ignore_index=True,axis=1)

#&#x8F93;&#x51FA;&#x7ED3;&#x679C;
       0      1     2     3     4     5
0   alex    python  88    xc    php   89
1   xm      java    79    xm    java  79
2   xh      go      68    xh    go    68
3   lc      js      96    lc    js    96
4   ll      html    66    ll    html  66

Original: https://blog.csdn.net/damadashen/article/details/126904544
Author: HM-hhxx!
Title: Pandas-04(缺失数据、分组、合并连接、级联)

原创文章受到原创版权保护。转载请注明出处:https://www.johngo689.com/738910/

转载文章受原作者版权保护。转载请注明原作者出处!

(0)

大家都在看

亲爱的 Coder【最近整理,可免费获取】👉 最新必读书单  | 👏 面试题下载  | 🌎 免费的AI知识星球