Pandas alignment operation
Alignment operation of Pandas
It is an important process of data cleaning. It can be calculated according to index alignment, and if it is not aligned, NaN can be added. Finally, NaN can be populated.
Alignment operation of Series 1. Series alignment by row and index
Sample code:
S1 = pd.Series (range (10,20), index = range (10)) S2 = pd.Series (range (20,25), index = range (5)) print ('S1:') print (S1)
Running result:
S1: 0 101 112 123 134 145 156 167 178 189 19dtype: int64s2: 0 201 212 223 234 24dtype: int642. Alignment operation of Series
Sample code:
S1 + S2
Running result:
0 30.01 32.02 34.03 36.04 38.05 NaN6 NaN7 NaN8 NaN9 NaNdtype: alignment of float64DataFrame 1. DataFrame alignment by row and column index
Sample code:
Df1 = pd.DataFrame (np.ones (2Power2), columns = ['axiao,' b']) df2 = pd.DataFrame (np.ones (3p3), columns = ['axiao,' baked,'c']) print ('df1:') print (df1) print ('') print ('df2:') print (df2)
Running result:
Df1: a b0 1.0 1.01 1.0 1.0df2: a b c0 1.0 1.0 1.01 1.0 1.0 1.02 1.0 1.0 1.02. Alignment operation of DataFrame
Sample code:
Df1 + df2
Running result:
A b c0 2.0 NaN1 2.0 NaN2 NaN populates unaligned data to perform operations fill_value uses add, sub, div, mul at the same time
Specify the padding value through fill_value, and the unaligned data will operate with the padding value.
Sample code:
Print (S1) print (S2) s1.add (S2, fill_value =-1) print (df1) print (df2) df1.sub (df2, fill_value = 2.)
Running result:
Print (S1) print (S2) s1.add (S2, fill_value =-1) print (df1) print (df2) df1.sub (df2, fill_value = 2.)
Running result:
# print (S1) 0101 112 123 134 145 156 167 178 189 19dtype: int64# print (S2) 0201 212 223 234 24dtype: int64# s1.add (S2) Fill_value =-1) 0 30.01 32.02 34.03 36.04 38.05 14.06 15.07 16.08 17.09 18.0dtype: float64# print (df1) a b1.0 1.01 1.0 1.0 print (df2) a b c01.0 1.01 1.0 1.02 1.0 1.0 1.0 df1.sub (df2, fill_value = 2.) A b c0 0.0 0.0 1.01 0.0 0.0 1.02 1.0 1.0 1.0