9.2 Pandas

Pandas

数据结构

import numpy as np
import pandas as pd
Series
s = pd.Series([1,3,6,np.nan,44,1)
print(s)
--->
0     1.0
1     3.0
2     6.0
3     NaN
4     44.0
5     1.0
dtype: float64
# Series的字符串表现形式为:索引在左边,值在右边。由于我们没有为数据指定索引,于是会自动
    创建一个0到N-1(N为长度)的整数型索引。
DataFrame
dates = pd.date_range('20160101', periods=6)
df = pd.DataFrame(np.random.randn(6,4), index=dates, columns=['a', 'b', 'c', 'd'])
print(df)
---> 
                   a         b         c         d
2016-01-01 -0.253065 -2.071051 -0.640515  0.613663
2016-01-02 -1.147178  1.532470  0.989255 -0.499761
2016-01-03  1.221656 -2.390171  1.862914  0.778070
2016-01-04  1.473877 -0.046419  0.610046  0.204672
2016-01-05 -1.584752 -0.700592  1.487264 -1.778293
2016-01-06  0.633675 -1.414157 -0.277066 -0.442545
# DataFrame是一个表格型的数据结构,其包含有一组有序的列,每列可以是不同的值类型(数值、字符串、布尔值等)
    DataFrame既有行索引也有列索引,它可以被看做由多个Series组成的大字典

df['b'] # 不能通过行号去获取, df['2016-01-01']是错误的
--->
2016-01-01   -2.071051
2016-01-02    1.532470
2016-01-03   -2.390171
2016-01-04   -0.046419
2016-01-05   -0.700592
2016-01-06   -1.414157
Freq: D, Name: b, dtype: float64

# 创建一组没给定行标签index和列标签columns时,index和columns会默认从0开始,0、1、3、4、5... 

# 还有一种生成df的方法, 这种方法能对每一列的数据进行特殊对待.
df = pd.DataFrame({'A' : 1,
                   'B' : pd.Timestamp(20130102),
                   'C' : pd.Series(1, index=list(range(4)), dtype='float32'),
                   'D' : np.array([3]*4, dtype='int32'),
                   'E' : pd.Categorical(['test', 'train', 'test', 'train']),
                   'F' : 'foo'})
print(df)
--->
     A          B    C  D      E    F
0  1.0 2013-01-02  1.0  3   test  foo
1  1.0 2013-01-02  1.0  3  train  foo
2  1.0 2013-01-02  1.0  3   test  foo
3  1.0 2013-01-02  1.0  3  train  foo
查看属性 dtypes
print(df.dtypes)
--->
df2.dtypes
A           float64
B    datetime64[ns]
C           float32
D             int32
E          category
F            object
dtype: object
查看行标签
print(df.index)
--->
Int64Index([0, 1, 2, 3], dtype='int64')

- 查看列标签(每行数据名称)
print(df.columns)
--->
Index(['A', 'B', 'C', 'D', 'E', 'F'], dtype='object')
只查看所有的值(忽略行列标签)
- 返回的类型是 np.array
print(df.values)
--->
array([[1.0, Timestamp('2013-01-02 00:00:00'), 1.0, 3, 'test', 'foo'],
       [1.0, Timestamp('2013-01-02 00:00:00'), 1.0, 3, 'train', 'foo'],
       [1.0, Timestamp('2013-01-02 00:00:00'), 1.0, 3, 'test', 'foo'],
       [1.0, Timestamp('2013-01-02 00:00:00'), 1.0, 3, 'train', 'foo']], dtype=object)
查看首尾项tail()、head()
print(df.tail()) # print(df.tail(10)) ---> 查看前十行
print(df.head())
查看数据的总结(如平均数、中位数等)
df.describe()
--->
         A    C    D
count  4.0  4.0  4.0  # 计数
mean   1.0  1.0  3.0  # 平均值
std    0.0  0.0  0.0  # 标准差
min    1.0  1.0  3.0  # 最小值
25%    1.0  1.0  3.0  # 下四分位数
50%    1.0  1.0  3.0  # 中位数
75%    1.0  1.0  3.0  # 上四分位数  四分位差=上四分位数-下四分位数,反映了中间50%数据的离散程度
max    1.0  1.0  3.0  # 最大值
翻转数据
print(df.T) # 或df.transpose()
--->
                     0                    1                    2                    3
A                    1                    1                    1                    1  
B  2013-01-02 00:00:00  2013-01-02 00:00:00  2013-01-02 00:00:00  2013-01-02 00:00:00  
C                    1                    1                    1                    1
D                    3                    3                    3                    3 
E                 test                train                 test                train
F                  foo                  foo                  foo                  foo 
排序数据
# 根据序号进行排序 sort_index
print(df.sort_index(axis=1, ascending=False)) # axis为0时,根据行序号排序,为1时根据列序号排序
--->                                          # ascending为True时,升序,否则降序
     F      E  D    C          B    A
0  foo   test  3  1.0 2013-01-02  1.0
1  foo  train  3  1.0 2013-01-02  1.0
2  foo   test  3  1.0 2013-01-02  1.0
3  foo  train  3  1.0 2013-01-02  1.0
根据数据值进行排序 sort_values(by, ascending=True)
print(df.sort_values(by='B')) # by='B'指的是对列序号为B的列进行排序
--->
     A          B    C  D      E    F
0  1.0 2013-01-02  1.0  3   test  foo
1  1.0 2013-01-02  1.0  3  train  foo
2  1.0 2013-01-02  1.0  3   test  foo
3  1.0 2013-01-02  1.0  3  train  foo

数据选择

dates = pd.date_range('20130101', periods=6)
df = pd.DataFrame(np.arange(24).reshape(6,4), index=dates, columns=['A','B','C','D'])
             A   B   C   D
2013-01-01   0   1   2   3
2013-01-02   4   5   6   7
2013-01-03   8   9  10  11
2013-01-04  12  13  14  15
2013-01-05  16  17  18  19
2013-01-06  20  21  22  23
简单筛选
选择某列
df['A'] 或 df.A  
--->
2013-01-01     0
2013-01-02     4
2013-01-03     8
2013-01-04    12
2013-01-05    16
2013-01-06    20
Freq: D, Name: A, dtype: int64

PS:The single bracket version gives a Pandas Series, the double bracket version gives a Pandas DataFrame.
type(df['A'])
---> pandas.core.series.Series

type(df[['A']])
---> pandas.core.frame.DataFrame
跨越多行或多列
# 通过行索引
df[0:3] # 选择1至3行
--->
            A  B   C   D
2013-01-01  0  1   2   3
2013-01-02  4  5   6   7
2013-01-03  8  9  10  11

# 通过行标签
df['20130102':'20130104'] # 全闭区间,包括这两个标签
--->
             A   B   C   D
2013-01-02   4   5   6   7
2013-01-03   8   9  10  11
2013-01-04  12  13  14  15
注意:如果df[3:3]将会是一个空对象。后者选择20130102到20130104标签之间的数据,并且包括这两个标签。
根据标签 loc
df.loc['20130102']
--->
A    4
B    5
C    6
D    7
Name: 2013-01-02 00:00:00, dtype: int64

df.loc[:, ['A','B']]
--->
             A   B
2013-01-01   0   1
2013-01-02   4   5
2013-01-03   8   9
2013-01-04  12  13
2013-01-05  16  17
2013-01-06  20  21

df.loc[:, 'A':'B']
--->
             A   B
2013-01-01   0   1
2013-01-02   4   5
2013-01-03   8   9
2013-01-04  12  13
2013-01-05  16  17
2013-01-06  20  21

df.loc['20130102', [['A','B']]
--->
A    4
B    5
Name: 2013-01-02 00:00:00, dtype: int64
根据索引 iloc
df.iloc[3,1]
--->
13

df.iloc[3:5, 1:3]
--->
             B   C
2013-01-04  13  14
2013-01-05  17  18

df.iloc[[1,3,5], 1:3]
--->
             B   C
2013-01-02   5   6
2013-01-04  13  14
2013-01-06  21  22
索引和标签的混合使用 ix (python强烈建议不使用)
df.ix[:3, ['A','C']]
--->
            A   C
2013-01-01  0   2
2013-01-02  4   6
2013-01-03  8  10
通过判断指令(Boolean indexing)
df[df.A>8]
--->
             A   B   C   D
2013-01-04  12  13  14  15
2013-01-05  16  17  18  19
2013-01-06  20  21  22  23

设置值

dates = pd.date_range('20130101', periods=6)
df = pd.DataFrame(np.arange(24).reshape(6,4), index=dates, columns=['A','B','C','D'])
--->
             A   B   C   D
2013-01-01   0   1   2   3
2013-01-02   4   5   6   7
2013-01-03   8   9  10  11
2013-01-04  12  13  14  15
2013-01-05  16  17  18  19
2013-01-06  20  21  22  23
根据位置设置 loc 和 iloc
df.iloc[2,2] = 1111
df.loc['20130101', 'B'] = 2222
--->
             A     B     C   D
2013-01-01   0  2222     2   3
2013-01-02   4     5     6   7
2013-01-03   8     9  1111  11
2013-01-04  12    13    14  15
2013-01-05  16    17    18  19
2013-01-06  20    21    22  23
根据条件设置
df[df.A>4] = 0
# 会影响所有的列
--->
             A     B     C    D
2013-01-01   0  2222     2    3
2013-01-02   4     5     6    7
2013-01-03   0     0     0    0
2013-01-04   0     0     0    0
2013-01-05   0     0     0    0
2013-01-06   0     0     0    0 
df.B[df.A>4] = 0
# 如果现在的判断条件是这样, 我们想要更改B中的数, 而更改的位置是取决于 A 的. 
# 对于A大于4的位置. 更改B在相应位置上的数为0.
--->
             A     B     C    D
2013-01-01   0  2222     2    3
2013-01-02   4     5     6    7
2013-01-03   8     0  1111   11
2013-01-04  12     0    14   15
2013-01-05  16     0    18   19
2013-01-06  20     0    22   23 
按行或列设置
如果对整列做批处理, 加上一列 ‘F’, 并将 F 列全改为 NaN, 如下:
df['F'] = np.nan
--->
             A     B     C   D   F
2013-01-01   0  2222     2   3 NaN
2013-01-02   4     5     6   7 NaN
2013-01-03   8     0  1111  11 NaN
2013-01-04  12     0    14  15 NaN
2013-01-05  16     0    18  19 NaN
2013-01-06  20     0    22  23 NaN
添加数据
用上面的方法也可以加上 Series 序列(但是长度必须对齐)
df['E'] = pd.Series(range(1,7), index=pd.date_range('20130101', periods=6))
--->
             A     B     C   D   F  E
2013-01-01   0  2222     2   3 NaN  1
2013-01-02   4     5     6   7 NaN  2
2013-01-03   8     0  1111  11 NaN  3
2013-01-04  12     0    14  15 NaN  4
2013-01-05  16     0    18  19 NaN  5
2013-01-06  20     0    22  23 NaN  6

处理数据

dates = pd.date_range('20130101', periods=6)
df = pd.DataFrame(np.arange(24).reshape(6,4), index=dates, columns=['A','B','C','D'])
df.iloc[0,1] = np.nan
df.iloc[1,2] = np.nan
--->
             A     B     C   D
2013-01-01   0   NaN   2.0   3
2013-01-02   4   5.0   NaN   7
2013-01-03   8   9.0  10.0  11
2013-01-04  12  13.0  14.0  15
2013-01-05  16  17.0  18.0  19
2013-01-06  20  21.0  22.0  23
删除某列pop()
column_deleted = df.pop('column_name)
# 返回的是被删除的列
dropna()
- 直接去掉有NaN的行或列
- 只是返回处理后的结果,但是df里面的元素没有被改变
df.dropna(axis=0,     # 0: 对行进行操作; 1: 对列进行操作
          how='any'   # 'any': 只要存在 NaN 就 drop 掉; 'all': 必须全部是 NaN 才 drop
          )
--->
             A     B     C   D
2013-01-03   8   9.0  10.0  11
2013-01-04  12  13.0  14.0  15
2013-01-05  16  17.0  18.0  19
2013-01-06  20  21.0  22.0  23
fillna()
- 将 NaN 的值用其他值代替, 比如代替成 0
- 只是返回处理后的结果,但是df里面的元素没有被改变
df.fillna(value=0)
--->
             A     B     C   D
2013-01-01   0   0.0   2.0   3
2013-01-02   4   5.0   0.0   7
2013-01-03   8   9.0  10.0  11
2013-01-04  12  13.0  14.0  15
2013-01-05  16  17.0  18.0  19
2013-01-06  20  21.0  22.0  23
isnull()
- 判断是否有缺失数据 NaN, 为 True 表示缺失数据:
df.isnull()
--->
                A      B      C      D
2013-01-01  False   True  False  False
2013-01-02  False  False   True  False
2013-01-03  False  False  False  False
2013-01-04  False  False  False  False
2013-01-05  False  False  False  False
2013-01-06  False  False  False  False

- 检测在数据中是否存在 NaN, 只要存在一个及以上就返回 True
np.any(df.isnull()) == True
--->
True
注意:这里与np.any()相对的还有np.all()
    np.any() 相当于 or  一个满足条件即可
    np.all() 相当于 and 所有条件满足才行

- 统计df中存在NaN的项
df.isnull().sum()
或者 df.isna().sum()

导入导出

pandas可以存取的文件格式有很多种,如csv、excel、json、html、pickle等
详见官方说明文件:https://pandas.pydata.org/pandas-docs/stable/user_guide/io.html

Format	    Data	                Reader	        Writer
Type        Description

text	    CSV	                    read_csv	    to_csv
text    	JSON	                read_json	    to_json
text	    HTML	                read_html	    to_html
text	    Local clipboard	        read_clipboard	to_clipboard
binary	    MS Excel	            read_excel	    to_excel
binary	    OpenDocument            read_excel	 
binary	    HDF5 Format	            read_hdf	    to_hdf
binary  	Feather Format	        read_feather	to_feather
binary	    Parquet Format	        read_parquet	to_parquet
binary	    Msgpack	                read_msgpack	to_msgpack
binary	    Stata	                read_stata	    to_stata
binary	    SAS	                    read_sas	 
binary	    Python Pickle Format	read_pickle	    to_pickle
SQL	        SQL	                    read_sql	    to_sql
SQL	        Google Big Query	    read_gbq	    to_gbq
读取csv
# 示范档案下载 - student.csv  https://github.com/MorvanZhou/tutorials/blob/master/numpy%26pandas/15_read_to/student.csv
dataset_path = tf,keras.utils.get_file('student.csv', 'https://github.com/MorvanZhou/tutorials/blob/master/numpy%26pandas/15_read_to/student.csv')
data = pd.read_csv(dataset_path) # 注意有个参数是 index_col=arg, arg可以是表示列数,从0开始,表示用第几列作为index标签(即第一列)
将文件保存为pickle格式
data.to_pickle(student.pickle)
或者
data.to_pickle(student.pkl)

合并 concat (concatenating)

- pandas处理多组数据的时候往往会要用到数据的合并处理
- 使用 concat 是一种基本的合并方式
- concat中有很多参数可以调整,合并成你想要的数据形式
axis(合并方向)
axis=0是预设值,因此未设定任何参数时,函数默认axis=0

import pandas as pd
import numpy as np

定义资料集
df1 = pd.DataFrame(np.ones((3,4))*0, columns=['a','b','c','d'])
df2 = pd.DataFrame(np.ones((3,4))*1, columns=['a','b','c','d'])
df3 = pd.DataFrame(np.ones((3,4))*2, columns=['a','b','c','d'])

#concat纵向合并 (axis=0加行,1则是加列)
res = pd.concat([df1, df2, df3], axis=0)

打印结果
print(res)
--->
     a    b    c    d
 0  0.0  0.0  0.0  0.0
 1  0.0  0.0  0.0  0.0
 2  0.0  0.0  0.0  0.0
 0  1.0  1.0  1.0  1.0
 1  1.0  1.0  1.0  1.0
 2  1.0  1.0  1.0  1.0
 0  2.0  2.0  2.0  2.0
 1  2.0  2.0  2.0  2.0
 2  2.0  2.0  2.0  2.0
 
仔细观察会发现结果的index是0, 1, 2, 0, 1, 2, 0, 1, 2,若要将index重置,请往下看
ignore_index(重置index)
承上一个例子,并将index_ignore设定为True
res = pd.concat([df1, df2, df3], axis=0, ignore_index=True)
--->
     a    b    c    d
 0  0.0  0.0  0.0  0.0
 1  0.0  0.0  0.0  0.0
 2  0.0  0.0  0.0  0.0
 3  1.0  1.0  1.0  1.0
 4  1.0  1.0  1.0  1.0
 5  1.0  1.0  1.0  1.0
 6  2.0  2.0  2.0  2.0
 7  2.0  2.0  2.0  2.0
 8  2.0  2.0  2.0  2.0

结果index变成0, 1, 2, 3, 4, 5, 6, 7, 8
join (合并方式)
inner 表示交集, outer表示并集
- join='outer'为预设值,因此未设定任何参数时,函数默认join='outer'
- 此方式是依照column来做纵向合并,有相同的column上下合并在一起
- 其他独自的column个自成列,原本没有值的位置皆以NaN填充

#定义资料集
df1 = pd.DataFrame(np.ones((3,4))*0, columns=['a','b','c','d'], index=[1,2,3])
df2 = pd.DataFrame(np.ones((3,4))*1, columns=['b','c','d','e'], index=[2,3,4])

#纵向"外"合并df1与df2
res = pd.concat([df1, df2], axis=0, join='outer') #  outer表示并集

print(res)
#     a    b    c    d    e
# 1  0.0  0.0  0.0  0.0  NaN
# 2  0.0  0.0  0.0  0.0  NaN
# 3  0.0  0.0  0.0  0.0  NaN
# 2  NaN  1.0  1.0  1.0  1.0
# 3  NaN  1.0  1.0  1.0  1.0
# 4  NaN  1.0  1.0  1.0  1.0
但只有相同的column合并在一起,其他的会被抛弃
#承上一个例子

#纵向"内"合并df1与df2
res = pd.concat([df1, df2], axis=0, join='inner') # inner 表示交集

#打印结果
print(res)
#     b    c    d
# 1  0.0  0.0  0.0
# 2  0.0  0.0  0.0
# 3  0.0  0.0  0.0
# 2  1.0  1.0  1.0
# 3  1.0  1.0  1.0
# 4  1.0  1.0  1.0

#重置index并打印结果
res = pd.concat([df1, df2], axis=0, join='inner', ignore_index=True) # inner 表示交集
print(res)
#     b    c    d
# 0  0.0  0.0  0.0
# 1  0.0  0.0  0.0
# 2  0.0  0.0  0.0
# 3  1.0  1.0  1.0
# 4  1.0  1.0  1.0
# 5  1.0  1.0  1.0
join_axes (依照 axes 合并)
#定义资料集
df1 = pd.DataFrame(np.ones((3,4))*0, columns=['a','b','c','d'], index=[1,2,3])
df2 = pd.DataFrame(np.ones((3,4))*1, columns=['b','c','d','e'], index=[2,3,4])

#依照 df1.index 进行横向合并
res = pd.concat([df1, df2], axis=1, join_axes=[df1.index])
- 现在python不推荐使用join_axes,而是用 .reindex() 来代替:
res = pd.concat([df1, df2], axis=1).reindex(df1.index)

#打印结果
print(res)
#     a    b    c    d    b    c    d    e
# 1  0.0  0.0  0.0  0.0  NaN  NaN  NaN  NaN
# 2  0.0  0.0  0.0  0.0  1.0  1.0  1.0  1.0
# 3  0.0  0.0  0.0  0.0  1.0  1.0  1.0  1.0

#移除join_axes,并打印结果
res = pd.concat([df1, df2], axis=1)
print(res)
#     a    b    c    d    b    c    d    e
# 1  0.0  0.0  0.0  0.0  NaN  NaN  NaN  NaN
# 2  0.0  0.0  0.0  0.0  1.0  1.0  1.0  1.0
# 3  0.0  0.0  0.0  0.0  1.0  1.0  1.0  1.0
# 4  NaN  NaN  NaN  NaN  1.0  1.0  1.0  1.0
append (添加数据)
#定义资料集
df1 = pd.DataFrame(np.ones((3,4))*0, columns=['a','b','c','d'])
df2 = pd.DataFrame(np.ones((3,4))*1, columns=['a','b','c','d'])
df3 = pd.DataFrame(np.ones((3,4))*1, columns=['a','b','c','d'])
s1 = pd.Series([1,2,3,4], index=['a','b','c','d'])

#将df2合并到df1的下面,以及重置index,并打印出结果
res = df1.append(df2, ignore_index=True)
print(res)
#     a    b    c    d
# 0  0.0  0.0  0.0  0.0
# 1  0.0  0.0  0.0  0.0
# 2  0.0  0.0  0.0  0.0
# 3  1.0  1.0  1.0  1.0
# 4  1.0  1.0  1.0  1.0
# 5  1.0  1.0  1.0  1.0

#合并多个df,将df2与df3合并至df1的下面,以及重置index,并打印出结果
res = df1.append([df2, df3], ignore_index=True)
print(res)
#     a    b    c    d
# 0  0.0  0.0  0.0  0.0
# 1  0.0  0.0  0.0  0.0
# 2  0.0  0.0  0.0  0.0
# 3  1.0  1.0  1.0  1.0
# 4  1.0  1.0  1.0  1.0
# 5  1.0  1.0  1.0  1.0
# 6  1.0  1.0  1.0  1.0
# 7  1.0  1.0  1.0  1.0
# 8  1.0  1.0  1.0  1.0

#合并series,将s1合并至df1,以及重置index,并打印出结果
res = df1.append(s1, ignore_index=True)
print(res)
#     a    b    c    d
# 0  0.0  0.0  0.0  0.0
# 1  0.0  0.0  0.0  0.0
# 2  0.0  0.0  0.0  0.0
# 3  1.0  2.0  3.0  4.0

合并 merge (功能更全)

- pandas中的merge和concat类似,但主要是用于两组有key column的数据,
    统一索引的数据. 通常也被用在Database的处理当中
根据一组key合并
left = pd.DataFrame({'key': ['K0', 'K1', 'K2', 'K3'],
                      'A': ['A0', 'A1', 'A2', 'A3'],
                      'B': ['B0', 'B1', 'B2', 'B3']})
                      
right = pd.DataFrame({'key': ['K0', 'K1', 'K2', 'K3'],
                      'C': ['C0', 'C1', 'C2', 'C3'],
                      'D': ['D0', 'D1', 'D2', 'D3']})
print(left)
#     A   B key
# 0  A0  B0  K0
# 1  A1  B1  K1
# 2  A2  B2  K2
# 3  A3  B3  K3

print(right)
#     C   D key
# 0  C0  D0  K0
# 1  C1  D1  K1
# 2  C2  D2  K2
# 3  C3  D3  K3

依据'key'column进行合并
res = pd.merge(left, right, on='key')

print(res)
      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
根据两组key合并
- 合并时有4种方法how = ['left', 'right', 'outer', 'inner'],默认值how='inner'
print(left)
#     A   B key1 key2
# 0  A0  B0   K0   K0
# 1  A1  B1   K0   K1
# 2  A2  B2   K1   K0
# 3  A3  B3   K2   K1

print(right)
#     C   D key1 key2
# 0  C0  D0   K0   K0
# 1  C1  D1   K1   K0
# 2  C2  D2   K1   K0
# 3  C3  D3   K2   K0

# 根据key1和key2 columns进行合并,并打印出四种结果['left', 'right', 'outer', 'inner']
res = pd.merge(left,right, on=['key1','key2'], how='inner') # 取交集
print(res)
#     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

res = pd.merge(left, right, on=['key1', 'key2'], how='outer') # 取并集(不存在的位置用NaN代替)
print(res)
#      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

res = pd.merge(left, right, on=['key1', 'key2'], how='left') # 根据左边的列表(即left), 
print(res)                                   # 要保证满足左边的列表,右边不存在的用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

res = pd.merge(left, right, on=['key1', 'key2'], how='right') # 同理,以右边列表为主
print(res)
#      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
# 3  NaN  NaN   K2   K0  C3  D3

Indicator (提示器)

- indicator=True会将合并的记录放在新的一列
res = pd.merge(df1, df2, on='col1', how='outer', indicator=True)
print(res)
#    col1 col_left  col_right      _merge
# 0   0.0        a        NaN   left_only
# 1   1.0        b        2.0        both
# 2   2.0      NaN        2.0  right_only
# 3   2.0      NaN        2.0  right_only


# 自定indicator column的名称,并打印出(既然indicator='indicator_column',说明其为True)
res = pd.merge(df1, df2, on='col1', how='outer', indicator='indicator_column')
print(res)
#    col1 col_left  col_right indicator_column
# 0   0.0        a        NaN        left_only
# 1   1.0        b        2.0             both
# 2   2.0      NaN        2.0       right_only
# 3   2.0      NaN        2.0       right_only

依据index合并

print(left)
#      A   B
# K0  A0  B0
# K1  A1  B1
# K2  A2  B2 

print(right)
#      C   D
# K0  C0  D0
# K2  C2  D2
# K3  C3  D3

#依据左右资料集的index进行合并,how='outer',并打印出,两边都要是True
res = pd.merge(left, right, left_index=True, right_index=True, how='outer')
print(res)
#       A    B    C    D
# K0   A0   B0   C0   D0
# K1   A1   B1  NaN  NaN
# K2   A2   B2   C2   D2
# K3  NaN  NaN   C3   D3

#依据左右资料集的index进行合并,how='inner',并打印出,两边都要是True
res = pd.merge(left, right, left_index=True, right_index=True, how='inner')
print(res)
#      A   B   C   D
# K0  A0  B0  C0  D0
# K2  A2  B2  C2  D2

解决overlapping(suffices,后缀)

boys  = pd.DataFrame({'k': ['K0', 'K1', 'K2'], 'age': [1, 2, 3]})
girls = pd.DataFrame({'k': ['K0', 'K0', 'K3'], 'age': [4, 5, 6]})

#使用suffixes解决overlapping的问题
res = pd.merge(boys, girls, on='k', suffixes=['_boy', '_girl'], how='inner')
print(res)
#    age_boy     k  age_girl
# 0        1    K0         4
# 1        1    K0         5

res = pd.merge(boys, girls, on='k', suffixes=['_boy', '_girl'], how='outer')
print(res)
#    age_boy     k  age_girl
# 0        1    K0         4
# 1        1    K0         5
# 2        2    K1       NaN
# 3        3    K2       NaN
# 4      NaN    K3         6

plot 出图

见matplotlib.pyplot
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值