当前位置:主页 > 查看内容

python数据分析之pandas超详细学习笔记

发布时间:2021-05-06 00:00| 位朋友查看

简介:文章目录 前言 一、series 1、创建一个series数据默认索引值 2、创建一个series数据自定义默认值 3、获取series的数据值 4、用字典来构建一个series数据 二、DataFrame 1、创建一个DataFrame数据 2、自定义行和列的值 3、获取值、行索引、列索引、转置 4、获……


  • 前排提醒:这篇(伪万字)文章篇幅略大,建议收藏观看。

作者:远方的星
CSDN:https://blog.csdn.net/qq_44921056
腾讯云:https://cloud.tencent.com/developer/column/91164
本文仅用于交流学习,未经作者允许,禁止转载,更勿做其他用途,违者必究。


前言

  • pandas,python+data+analysis的组合缩写,是python中基于numpy和matplotlib的第三方数据分析库,与后两者共同构成了python数据分析的基础工具包,享有数分三剑客之名。

文章开始前,需要进行库的安装:
打开cmd,依次输入以下三个命令即可。

pip install pandas -i https://pypi.tuna.tsinghua.edu.cn/simple
pip install numpy -i https://pypi.tuna.tsinghua.edu.cn/simple
pip install matplotlib -i https://pypi.tuna.tsinghua.edu.cn/simple

这里使用的是清华源,提高安装速度。

一、series

series是一个一维数组,线性的数据结构。

1、创建一个series数据(默认索引值)

  • 使用pandas.Series()函数
import pandas as pd

# 创建一个series数据,默认索引值
s1 = pd.Series([1, 3, 14, 521])
print(s1)

输出:

0      1
1      3
2     14
3    521
dtype: int64

提示:命名文件的时候文件命不要以pandas命名。

2、创建一个series数据(自定义默认值)

import pandas as pd

# 创建一个series数据,索引值自定义
s2 = pd.Series([1, 3, 14, 521], index=['第一个数', '第二个数', '第三个数', '第四个数'])
print(s2)

输出:

第一个数      1
第二个数      3
第三个数     14
第四个数    521
dtype: int64

3、获取series的数据值

  • 使用pandas.values()函数
import pandas as pd

# 提取series的数据的值
s3 = pd.Series([1, 3, 14, 521])
# 直接获取值
print(s3.values)
print('-------分割线-------')
# 根据索引获取值
print(s3[0:3])

输出:

[  1   3  14 521]
-------分割线-------
0     1
1     3
2    14
dtype: int64

4、用字典来构建一个series数据

series可以看作一个定长的有序字典

import pandas as pd

dict = {"数学": 130, "专业课": 140, "政治": 80, "英语": 70}
s4 = pd.Series(dict)
print(s4)

输出:

数学     130
专业课    140
政治      80
英语      70
dtype: int64

二、DataFrame

1、创建一个DataFrame数据

  • 使用pandas.DataFrame函数

①:

import pandas as pd

data = {
    'class': [1, 2, 3, 4],
    'people': [16, 15, 17, 18]
}
df1 = pd.DataFrame(data)
print(df1)

输出:

   class  people
0      1      16
1      2      15
2      3      17
3      4      18

②:利用np.arange()函数,用法可参考np.arange()用法

import pandas as pd
import numpy as np
df2 = pd.DataFrame(np.arange(8).reshape(2, 4))
print(df2)

输出:

   0  1  2  3
0  0  1  2  3
1  4  5  6  7

2、自定义行和列的值

import pandas as pd
import numpy as np
df3 = pd.DataFrame(np.arange(8).reshape(2, 4), index=['a', 'b'], columns=['11', '22', '33', '44'])
print(df3)

输出:

   11  22  33  44
a   0   1   2   3
b   4   5   6   7

3、获取值、行索引、列索引、转置

  • 使用valuesindexcolumnsaxesT
import pandas as pd
import numpy as np
df4 = pd.DataFrame(np.arange(8).reshape(2, 4), index=['a', 'b'], columns=['11', '22', '33', '44'])
print('--------原数据-------')
print(df4)
print('-------获取值--------')
print(df4.values)
print('-------获取行索引--------')
print(df4.index)
print('-------获取列索引--------')
print(df4.columns)
print('-------获取行及列的索引值--------')
print(df4.axes)
print('-------获取转置-------')
print(df4.T)

输出:

--------原数据-------
   11  22  33  44
a   0   1   2   3
b   4   5   6   7
-------获取值--------
[[0 1 2 3]
 [4 5 6 7]]
-------获取行索引--------
Index(['a', 'b'], dtype='object')
-------获取列索引--------
Index(['11', '22', '33', '44'], dtype='object')
-------获取行及列的索引值--------
[Index(['a', 'b'], dtype='object'), Index(['11', '22', '33', '44'], dtype='object')]
-------获取转置值-------
    a  b
11  0  4
22  1  5
33  2  6
44  3  7

4、获取统计变量

  • 使用pandas.describe()函数
import pandas as pd

data = {'year': [2018, 2019, 2020, 2021],
        'income': [10000, 20000, 30000, 40000],
        'pay': [5000, 15000, 20000, 30000]
}
df5 = pd.DataFrame(data)
print(df5.describe())

输出:

              year        income           pay
count     4.000000      4.000000      4.000000
mean   2019.500000  25000.000000  17500.000000
std       1.290994  12909.944487  10408.329997
min    2018.000000  10000.000000   5000.000000
25%    2018.750000  17500.000000  12500.000000
50%    2019.500000  25000.000000  17500.000000
75%    2020.250000  32500.000000  22500.000000
max    2021.000000  40000.000000  30000.000000

注解:

   count:数量统计,此列共有多少有效值
   mean:均值
   std:标准差
   min:最小值
   25%:四分之一分位数
   50%:二分之一分位数
   75%:四分之三分位数
   max:最大值
   

5、根据行、列、值进行排序

  • 使用sort_index()sort_values()
import pandas as pd
import numpy as np
df6 = pd.DataFrame(np.arange(8).reshape(2, 4), index=['b', 'a'], columns=['22', '11', '44', '33'])
print('--------原数据-------')
print(df6)
print('--------行排序-------')
print(df6.sort_index(axis=0))
print('--------列排序-------')
print(df6.sort_index(axis=1))
print('--------值排序(对33列里的值进行排序)-------')
print(df6.sort_values(by='33'))

输出:

--------原数据-------
   22  11  44  33
b   0   1   2   3
a   4   5   6   7
--------行排序-------
   22  11  44  33
a   4   5   6   7
b   0   1   2   3
--------列排序-------
   11  22  33  44
b   1   0   3   2
a   5   4   7   6
--------值排序(33列里的值进行排序)-------
   22  11  44  33
b   0   1   2   3
a   4   5   6   7

三、pandas选择数据

import pandas as pd
import numpy as np
dates = pd.date_range('20210301', periods=6)
df1 = pd.DataFrame(np.arange(24).reshape((6, 4)), index=dates, columns=['A', 'B', 'C', 'D'])
print(df1)

输出:

             A   B   C   D
2021-03-01   0   1   2   3
2021-03-02   4   5   6   7
2021-03-03   8   9  10  11
2021-03-04  12  13  14  15
2021-03-05  16  17  18  19
2021-03-06  20  21  22  23
  • 注:以下所有操作均以上述结果为基础

1、获取一列的series数据和行数据

print('----将DataFrame的一个列获取为一个series数据----')
a = df1.A  # 或者写成 df1['A']
print(a)
print('-------获取前两行数据------')
print(df1[0:2])

输出:

----将DataFrame的一个列获取为一个series数据----
2021-03-01     0
2021-03-02     4
2021-03-03     8
2021-03-04    12
2021-03-05    16
2021-03-06    20
Freq: D, Name: A, dtype: int32
-------获取前两行数据------
            A  B  C  D
2021-03-01  0  1  2  3
2021-03-02  4  5  6  7

2、通过标签获取数据

  • 使用loc
print('------行标签-----')
print(df1.loc['20210302'])
print('------行和列混合标签--------')
print(df1.loc['20210301', ['A', 'C']])
print('-------全选行但不全选列-------')
print(df1.loc[:, ['A', 'C']])
print('-------全选列但不全选行-------')
print(df1.loc[['20210302', '20210304'], :])

输出:

------行标签-----
A    4
B    5
C    6
D    7
Name: 2021-03-02 00:00:00, dtype: int32
------行和列混合标签--------
A    0
C    2
Name: 2021-03-01 00:00:00, dtype: int32
-------全选行但不全选列-------
             A   C
2021-03-01   0   2
2021-03-02   4   6
2021-03-03   8  10
2021-03-04  12  14
2021-03-05  16  18
2021-03-06  20  22
-------全选列但不全选行-------
             A   B   C   D
2021-03-02   4   5   6   7
2021-03-04  12  13  14  15

3、通过位置获取数据

  • 使用iloc
print('-------第四行------')
print(df1.iloc[3])
print('-------二到三行,三到四列------')
print(df1.iloc[1:3, 2:4])
print('-------第2,3,4行,3、4列')
print(df1.iloc[[1, 2, 3], [2, 3]])

输出:

-------第四行------
A    12
B    13
C    14
D    15
Name: 2021-03-04 00:00:00, dtype: int32
-------二到三行,三到四列------
             C   D
2021-03-02   6   7
2021-03-03  10  11
-------234行,34列
             C   D
2021-03-02   6   7
2021-03-03  10  11
2021-03-04  14  15

4、对某一列的数据进行判断

print(df1.A)
print('---------------------分割线--------------------')
print(df1.A > 6)

输出:

2021-03-01     0
2021-03-02     4
2021-03-03     8
2021-03-04    12
2021-03-05    16
2021-03-06    20
Freq: D, Name: A, dtype: int32
---------------------分割线--------------------
2021-03-01    False
2021-03-02    False
2021-03-03     True
2021-03-04     True
2021-03-05     True
2021-03-06     True
Freq: D, Name: A, dtype: bool

四、pandas赋值及操作

import pandas as pd
import numpy as np
dates = pd.date_range('20210301', periods=6)
df1 = pd.DataFrame(np.arange(24).reshape((6, 4)), index=dates, columns=['A', 'B', 'C', 'D'])
print(df1)

输出:

             A   B   C   D
2021-03-01   0   1   2   3
2021-03-02   4   5   6   7
2021-03-03   8   9  10  11
2021-03-04  12  13  14  15
2021-03-05  16  17  18  19
2021-03-06  20  21  22  23
  • 以下结果均为上述为基础

1、替换原有值

①根据位置替换数据

df1.iloc[1, 2] = 100
print(df1)

输出:

             A   B    C   D
2021-03-01   0   1    2   3
2021-03-02   4   5  100   7
2021-03-03   8   9   10  11
2021-03-04  12  13   14  15
2021-03-05  16  17   18  19
2021-03-06  20  21   22  23

②根据标签替换数据

df1.loc["20210304", 'B'] = 200
print(df1)

输出:

             A    B   C   D
2021-03-01   0    1   2   3
2021-03-02   4    5   6   7
2021-03-03   8    9  10  11
2021-03-04  12  200  14  15
2021-03-05  16   17  18  19
2021-03-06  20   21  22  23

③根据条件替换数据
Ⅰ.

df1[df1.D > 10] = 0  # df1.D > 10的作用是找到D列数据大于10的所有行数据
print(df1)

输出:

            A  B  C  D
2021-03-01  0  1  2  3
2021-03-02  4  5  6  7
2021-03-03  0  0  0  0
2021-03-04  0  0  0  0
2021-03-05  0  0  0  0
2021-03-06  0  0  0  0

Ⅱ.

df1.A[df1.A == 8] = 300  # 找到A列等于8的所有数据,并替换成300
print(df1)

输出:

              A   B   C   D
2021-03-01    0   1   2   3
2021-03-02    4   5   6   7
2021-03-03  300   9  10  11
2021-03-04   12  13  14  15
2021-03-05   16  17  18  19
2021-03-06   20  21  22  23

2、插入行、列

①通过series数据的形式插入

df1['F'] = pd.Series(['1', '2', '3', '4', '5', '6'], index=dates)
print(df1)

输出:

             A   B   C   D  F
2021-03-01   0   1   2   3  1
2021-03-02   4   5   6   7  2
2021-03-03   8   9  10  11  3
2021-03-04  12  13  14  15  4
2021-03-05  16  17  18  19  5
2021-03-06  20  21  22  23  6

②通过append函数插入(行操作)

s = pd.Series([1, 2, 3, 4], index=['A', 'B', 'C', 'D'])
s.name = 'new'
df2 = df1.append(s)
print(df2)

输出:

                      A   B   C   D
2021-03-01 00:00:00   0   1   2   3
2021-03-02 00:00:00   4   5   6   7
2021-03-03 00:00:00   8   9  10  11
2021-03-04 00:00:00  12  13  14  15
2021-03-05 00:00:00  16  17  18  19
2021-03-06 00:00:00  20  21  22  23
new                   1   2   3   4

③通过insert函数插入(列操作)

df1.insert(2, 'E', [1, 2, 3, 4, 5, 6])  # 在第二列的右边插入一个新的E列
print(df1)

输出:

             A   B  E   C   D
2021-03-01   0   1  1   2   3
2021-03-02   4   5  2   6   7
2021-03-03   8   9  3  10  11
2021-03-04  12  13  4  14  15
2021-03-05  16  17  5  18  19
2021-03-06  20  21  6  22  23

3、删除行、列

①删除行

df2 = df1.drop('20210302', axis=0)  # 删除20210302行
print(df2)

这里报错了!!!

具体博主还没有解决,但我试了另外一个例子是可以运行的,请看:

import pandas as pd
import numpy as np
df1 = pd.DataFrame(np.arange(24).reshape((6, 4)), index=['1', '2', '3', '4', '5', '6'], columns=['A', 'B', 'C', 'D'])
df2 = df1.drop('2', axis=0)  # 删除‘2’行
print('--------------原数据--------------')
print(df1)
print('--------------删除后的数据-------------')
print(df2)

输出:

--------------原数据--------------
    A   B   C   D
1   0   1   2   3
2   4   5   6   7
3   8   9  10  11
4  12  13  14  15
5  16  17  18  19
6  20  21  22  23
--------------删除后的数据-------------
    A   B   C   D
1   0   1   2   3
3   8   9  10  11
4  12  13  14  15
5  16  17  18  19
6  20  21  22  23

这里是成功把‘2’这行给删除掉了。

②删除列

df2 = df1.drop('A', axis=1)  # 删除A列
print(df2)

输出:

             B   C   D
2021-03-01   1   2   3
2021-03-02   5   6   7
2021-03-03   9  10  11
2021-03-04  13  14  15
2021-03-05  17  18  19
2021-03-06  21  22  23

五、pandas对于空数据的处理

import pandas as pd
import numpy as np
dates = pd.date_range('20210301', periods=6)
df1 = pd.DataFrame(np.arange(24).reshape((6, 4)), index=dates, columns=['A', 'B', 'C', 'D'])
df2 = pd.DataFrame(df1, index=dates, columns=['A', 'B', 'C', 'D', 'E', 'F'])
s1 = pd.Series([3, 4, 6, 7], index=dates[:4])  # 对第一个到第四个数据进行赋值
s2 = pd.Series([32, 5, 2, 1], index=dates[2:])  # 对第三个数据到最后一个数据进行赋值
df2['E'] = s1
df2['F'] = s2
print(df2)

输出:

             A   B   C   D    E     F
2021-03-01   0   1   2   3  3.0   NaN
2021-03-02   4   5   6   7  4.0   NaN
2021-03-03   8   9  10  11  6.0  32.0
2021-03-04  12  13  14  15  7.0   5.0
2021-03-05  16  17  18  19  NaN   2.0
2021-03-06  20  21  22  23  NaN   1.0
  • 以下结果均为上述为基础

1、删除空值所在的行或者列

  • 使用dropna函数
# axis中的0代表行,1代表列。how中的any表示,含有空值即删除 ,all代表全部为空值才删除
print(df2.dropna(axis=0, how='any'))

输出:

             A   B   C   D    E     F
2021-03-03   8   9  10  11  6.0  32.0
2021-03-04  12  13  14  15  7.0   5.0

2、对空值进行赋值

  • 使用fillna函数
# 对空值进行赋值,此处赋值为100
print(df2.fillna(value=100))

输出:

             A   B   C   D      E      F
2021-03-01   0   1   2   3    3.0  100.0
2021-03-02   4   5   6   7    4.0  100.0
2021-03-03   8   9  10  11    6.0   32.0
2021-03-04  12  13  14  15    7.0    5.0
2021-03-05  16  17  18  19  100.0    2.0
2021-03-06  20  21  22  23  100.0    1.0

3、判断数据是否为空值

  • 使用isnull函数,空值返回True,非空值返回Flase
print(df2.isnull())

输出:

                A      B      C      D      E      F
2021-03-01  False  False  False  False  False   True
2021-03-02  False  False  False  False  False   True
2021-03-03  False  False  False  False  False  False
2021-03-04  False  False  False  False  False  False
2021-03-05  False  False  False  False   True  False
2021-03-06  False  False  False  False   True  False

六、pandas读取和存入csv文件

1、读取文件

file = pd.read_csv('csv文件的路径', encoding='编码格式')  # 编码格式如gbk,utf-8等

2、保存文件

file.to_csv('文件要保存到的路径')

七、pandas合并

1、横向拼接、纵向拼接

  • 新建三个dataframe数据
import pandas as pd
import numpy as np
df1 = pd.DataFrame(np.arange(12).reshape((3,4)),columns=['a','b','c','d'])
df2 = pd.DataFrame(np.arange(12,24).reshape((3,4)),columns=['a','b','c','d'])
df3 = pd.DataFrame(np.arange(24,36).reshape((3,4)),columns=['a','b','c','d'])
print(df1)
print(df2)
print(df3)

输出:

   a  b   c   d
0  0  1   2   3
1  4  5   6   7
2  8  9  10  11
    a   b   c   d
0  12  13  14  15
1  16  17  18  19
2  20  21  22  23
    a   b   c   d
0  24  25  26  27
1  28  29  30  31
2  32  33  34  35
  • 实现横向和纵向合并
df4 = pd.concat([df1,df2,df3],axis=0)#纵向合并
df5 = pd.concat([df1,df2,df3],axis=1)#横向合并
print('---------------纵向合并结果---------------')
print(df4)
print('---------------横向合并结果---------------')
print(df5)

输出:

---------------纵向合并结果---------------
    a   b   c   d
0   0   1   2   3
1   4   5   6   7
2   8   9  10  11
0  12  13  14  15
1  16  17  18  19
2  20  21  22  23
0  24  25  26  27
1  28  29  30  31
2  32  33  34  35
---------------横向合并结果---------------
   a  b   c   d   a   b   c   d   a   b   c   d
0  0  1   2   3  12  13  14  15  24  25  26  27
1  4  5   6   7  16  17  18  19  28  29  30  31
2  8  9  10  11  20  21  22  23  32  33  34  35
  • 细心的小伙伴可能已经发现了,纵向合并时,index值看上去不太舒服。可以在上述代码的基础上加以补充,实现index值的改变。
df4 = pd.concat([df1,df2,df3],axis=0,ignore_index=True)  # ignore_index=True的作用是不考虑表原来的index
print(df4)

输出:

    a   b   c   d
0   0   1   2   3
1   4   5   6   7
2   8   9  10  11
3  12  13  14  15
4  16  17  18  19
5  20  21  22  23
6  24  25  26  27
7  28  29  30  31
8  32  33  34  35

2、获取两个表的交集和并集

join参数的属性,如果为’inner’得到的是两表的交集,如果是outer,得到的是两表的并集。

  • 新建两个dataframe数据
import pandas as pd
import numpy as np
df1 = pd.DataFrame(np.arange(12).reshape((3,4)),columns=['a','b','c','f'])
df2 = pd.DataFrame(np.arange(12,24).reshape((3,4)),columns=['a','c','d','e'])
print(df1)
print(df2)

输出:

   a  b   c   f
0  0  1   2   3
1  4  5   6   7
2  8  9  10  11
    a   c   d   e
0  12  13  14  15
1  16  17  18  19
2  20  21  22  23
  • 实现得到两张表的交集和并集
df3 = pd.concat([df1,df2],join='outer',ignore_index=True)
df4 = pd.concat([df1,df2],join='inner',ignore_index=True)
print('------------------并集结果-------------------')
print(df3)
print('------------------交集结果-------------------')
print(df4)

输出:

------------------并集结果-------------------
    a    b   c     f     d     e
0   0  1.0   2   3.0   NaN   NaN
1   4  5.0   6   7.0   NaN   NaN
2   8  9.0  10  11.0   NaN   NaN
3  12  NaN  13   NaN  14.0  15.0
4  16  NaN  17   NaN  18.0  19.0
5  20  NaN  21   NaN  22.0  23.0
------------------交集结果-------------------
    a   c
0   0   2
1   4   6
2   8  10
3  12  13
4  16  17
5  20  21

注意:去并集时,空值的地方用NaN填充

新版本pandas已经删除了join_axes,两个dataframe按照同一列合并的话,可以改用merge

八、pandas合并——merge

  • 用字典新建两个dataframe数据:
import pandas as pd
left = pd.DataFrame({'key1':['K0','K0','K1','K2'],
                     'key2':['K0','K1','K0','K1'],
                     'A':['A0','A1','A2','A3'],
                     'B':['B0','B1','B2','B3']})

right = pd.DataFrame({'key1':['K0','K1','K1','K3'],
                      'key2':['K0','K0','K0','K0'],
                     'C':['C0','C1','C2','C3'],
                     'D':['D0','D1','D2','D3']})

print(left)
print(right)

输出:

  key1 key2   A   B
0   K0   K0  A0  B0
1   K0   K1  A1  B1
2   K1   K0  A2  B2
3   K2   K1  A3  B3
  key1 key2   C   D
0   K0   K0  C0  D0
1   K1   K0  C1  D1
2   K1   K0  C2  D2
3   K3   K0  C3  D3

  • 使用merge进行合并

  • on: 要加入的列或索引级别名称。 必须在左侧和右侧DataFrame对象中找到。

  • 其中how有四个参数:inner、outer、left、right,默认值是inner。 inner的作用是取交集;
    outer的作用是取并集;
    left的作用是只取左边的表有值的情况;
    right的作用是只取右边的表有值的情况。
    left和rigth的结果是outer的子集。

res_1 = pd.merge(left,right,on=['key1','key2'],how='inner')
res_2 = pd.merge(left,right,on=['key1','key2'],how='outer')
res_3 = pd.merge(left,right,on=['key1','key2'],how='left')
res_4 = pd.merge(left,right,on=['key1','key2'],how='right')
print('-------------------------how的参数取inner的结果--------------------')
print(res_1)
print('-------------------------how的参数取outer的结果--------------------')
print(res_2)
print('-------------------------how的参数取left的结果---------------------')
print(res_3)
print('-------------------------how的参数取right的结果--------------------')
print(res_4)

输出:

-------------------------how的参数取inner的结果--------------------
  key1 key2   A   B   C   D
0   K0   K0  A0  B0  C0  D0
1   K1   K0  A2  B2  C1  D1
2   K1   K0  A2  B2  C2  D2
-------------------------how的参数取outer的结果--------------------
  key1 key2    A    B    C    D
0   K0   K0   A0   B0   C0   D0
1   K0   K1   A1   B1  NaN  NaN
2   K1   K0   A2   B2   C1   D1
3   K1   K0   A2   B2   C2   D2
4   K2   K1   A3   B3  NaN  NaN
5   K3   K0  NaN  NaN   C3   D3
-------------------------how的参数取left的结果---------------------
  key1 key2   A   B    C    D
0   K0   K0  A0  B0   C0   D0
1   K0   K1  A1  B1  NaN  NaN
2   K1   K0  A2  B2   C1   D1
3   K1   K0  A2  B2   C2   D2
4   K2   K1  A3  B3  NaN  NaN
-------------------------how的参数取right的结果--------------------
  key1 key2    A    B   C   D
0   K0   K0   A0   B0  C0  D0
1   K1   K0   A2   B2  C1  D1
2   K1   K0   A2   B2  C2  D2
3   K3   K0  NaN  NaN  C3  D3
  • 加入indicator参数可以查看merge的详细信息
    如:
res = pd.merge(left,right,on=['key1','key2'],how='outer',indicator=True)
print(res)

输出:

  key1 key2    A    B    C    D      _merge
0   K0   K0   A0   B0   C0   D0        both
1   K0   K1   A1   B1  NaN  NaN   left_only
2   K1   K0   A2   B2   C1   D1        both
3   K1   K0   A2   B2   C2   D2        both
4   K2   K1   A3   B3  NaN  NaN   left_only
5   K3   K0  NaN  NaN   C3   D3  right_only

indicator的值也可以是字符串参数,在这种情况下,指标函数将使用传递的字符串的值作为指标列的名称。

  • 以index为链接键需要同时设置left_index= True 和 right_index= True
    如:
res = pd.merge(left,right,left_index=True,right_index=True,how='outer')
print(res)

输出:

  key1_x key2_x   A   B key1_y key2_y   C   D
0     K0     K0  A0  B0     K0     K0  C0  D0
1     K0     K1  A1  B1     K1     K0  C1  D1
2     K1     K0  A2  B2     K1     K0  C2  D2
3     K2     K1  A3  B3     K3     K0  C3  D3
  • sort对链接的键值进行排序:
res = pd.merge(left,right,on=['key1','key2'],how='outer',sort=True)
print(res)

输出:

  key1 key2    A    B    C    D
0   K0   K0   A0   B0   C0   D0
1   K0   K1   A1   B1  NaN  NaN
2   K1   K0   A2   B2   C1   D1
3   K1   K0   A2   B2   C2   D2
4   K2   K1   A3   B3  NaN  NaN
5   K3   K0  NaN  NaN   C3   D3

九、pandas plot 画图函数

import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
data = pd.DataFrame(np.random.randn(1000,4),index=np.arange(1000),columns=['A','B','C','D'])
data = data.cumsum()
print(data.head())
data.plot()
plt.show()

输出:
在这里插入图片描述

注解:
1、numpy.random.randn():返回一个或一组样本,具有标准正态分布。此处为10004列的数据
2、data.head(),获取data的前几个数据,head的默认值为5
3、data.cumsum()的一个作用是可以求累加量

十、 参考文章及学习视频

博文中有一些地方的例子是直接引用学习视频中的例子,卑微博主在线感激!
下面是博主参考的一些其它博文和学习视频。
pandas documentation
pandas快速入门
pandas plot的画图命令
学习视频
参考文章5
参考文章6
参考文章7
参考文章8

十一、Blogger’s speech

如有不足,还请大佬评论区留言或私信我,我会进行补充。

感谢您的支持,希望可以点赞,关注,收藏,一键三连哟。

作者:远方的星
CSDN:https://blog.csdn.net/qq_44921056
腾讯云:https://cloud.tencent.com/developer/column/91164
本文仅用于交流学习,未经作者允许,禁止转载,更勿做其他用途,违者必究。

;原文链接:https://blog.csdn.net/qq_44921056/article/details/115419404
本站部分内容转载于网络,版权归原作者所有,转载之目的在于传播更多优秀技术内容,如有侵权请联系QQ/微信:153890879删除,谢谢!

推荐图文


随机推荐