pandas合并重叠数据(combine_first())
前面介绍了按列或者按行连接数据的方法,但在数据合并处理中,还有一种数据组合的处理方法,那就是合并重叠数据。
合并重叠数据使用 combine_first() 函数,该函数的语法格式如下。
该函数的作用是用函数参数对象中的数据为函数调用对象的缺失数据“打补丁”,即填充函数调用对象中的数据缺失值。
其示例代码 example1.py 如下。
最后一条输出语句的输出结果如下。
合并重叠数据使用 combine_first() 函数,该函数的语法格式如下。
obj1.combine_first(obj2)
其中,obj1 为函数调用对象的数据集;obj2 为函数参数对象的数据集。该函数的作用是用函数参数对象中的数据为函数调用对象的缺失数据“打补丁”,即填充函数调用对象中的数据缺失值。
其示例代码 example1.py 如下。
# -*- coding: utf-8 -*- import numpy as np import pandas as pd s1 = pd.Series([2,np.nan, 4.2, np.nan, 5.5, np.nan], index=['a', 'b', 'c', 'd', 'e', 'f']) s2 = pd.Series(np.arange(len(s1), dtype=np.float64), index=['a', 'b', 'c', 'd', 'e', 'f']) result = s2[:-3].combine_first(s1[3:]) print(s1,'\n',s2,'\n',result) df1 = pd.DataFrame({'a': [np.nan,2., 4., np.nan], 'b': [1.,np.nan, 3., np.nan], 'c': range(2, 18, 4)}) df2 = pd.DataFrame({'a': [3., np.nan,5., 7., 9.], 'b': [np.nan, 2., 4., 6., 8.]}) result1 = df1.combine_first(df2) print(df1,'\n',df2,'\n',result1)
最后一条输出语句的输出结果如下。
a b c 0 NaN 1.0 2 1 2.0 NaN 6 2 4.0 3.0 10 3 NaN NaN 14 a b 0 3.0 NaN 1 NaN 2.0 2 5.0 4.0 3 7.0 6.0 4 9.0 8.0 a b c 0 3.0 1.0 2.0 1 2.0 2.0 6.0 2 4.0 3.0 10.0 3 7.0 6.0 14.0 4 9.0 8.0 NaN