pandas DataFrame(5)-合并DataFrame与Series
之前已经学过DataFrame与DataFrame相加,Series与Series相加,这篇介绍下DataFrame与Series的相加:
import pandas as pd s = pd.Series([1, 2, 3, 4]) df = pd.DataFrame({ 0: [10, 20, 30, 40], 1: [50, 60, 70, 80], 2: [90, 100, 110, 120], 3: [130, 140, 150, 160] }) print df + s
0 1 2 3
0 11 52 93 134
1 21 62 103 144
2 31 72 113 154
3 41 82 123 164
首先将Series的索引值和DataFrame的索引值相匹配, s[0] 是 1 , df[0] 是 [10,20,30,40]
然后相当于向量化运算: [10,20,30,40] + 1 ,得到: [11,21,31,41]
无论索引值怎么变化,都是按照这个套路来进行运算:
s = pd.Series([1, 2, 3, 4]) df = pd.DataFrame({0: [10], 1: [20], 2: [30], 3: [40]}) print df + s
0 1 2 3
0 11 22 33 44
s = pd.Series([1, 2, 3, 4]) df = pd.DataFrame({0: [10, 20, 30, 40]}) print df + s