当想对一个Series和一个Dataframe进行算数运算时,最好的方式是运用numpy中的广播机制,来进行运算,这样的速度要更快,而且可以规避索引不同带来的问题。
合并时最让人头大的,就是索引不同。
当索引相同时,借用一下这位的例子(120条消息) DataFrame和Series的简单运算(加减乘除)_series相减_小白tree的博客-优快云博客
比如说:在下面的例子中,frame和series由于行索引相同,所以pandas可以自动广播,进行运算
frame = pd.DataFrame(np.arange(9).reshape(3,3), columns=['a','b','c'], index=['one', 'two', 'threee'])
print(frame)
a b c
one 0 1 2
two 3 4 5
threee 6 7 8
series = frame['b']
print(series)
one 1
two 4
threee 7
frame.add(series, axis=0)#加
a b c
one 1 2 3
two 7 8 9
threee 13 14 15
#frame.sub(series, axis=0)#减
#frame.div(series, axis=0)#除
frame.mul(series, axis=0)#乘
a b c
one 0 1 2
two 12 16 20
threee 42 49 56
但是一旦索引不同,就完蛋了。
比如,接着上面的例子:
series.index=[0,1,2]#将series的索引重置
print(series)
0 1
1 4
2 7
frame.add(series, axis=1)
a b c 0 1 2
one NaN NaN NaN NaN NaN NaN
two NaN NaN NaN NaN NaN NaN
threee NaN NaN NaN NaN NaN NaN
frame.add(series, axis=0)
a b c
0 NaN NaN NaN
1 NaN NaN NaN
2 NaN NaN NaN
one NaN NaN NaN
threee NaN NaN NaN
two NaN NaN NaN
此时不论怎么加都是错的。这正是因为索引轴不同导致的。
那么这个时候,最好的办法就是用numpy中的广播机制函数,np.broadcast_to()函数
这个函数大家可以自己去了解一下。
这个函数的主要功能,就是把原来的一列数据,给“复制”成多列一样的数据,这样去计算。
那么接下来演示一下:
series #这是现在的series
Out[25]:
0 1
1 4
2 7
np.broadcast_to(series,(3,3))#将series按行广播
array([[1, 4, 7],
[1, 4, 7],
[1, 4, 7]])
np.broadcast_to(series[:,None],(3,3))#将series按列广播
array([[1, 1, 1],
[4, 4, 4],
[7, 7, 7]])
#此时就可以正常运算了
frame+np.broadcast_to(series[:,None],(3,3))#series[:,None]可以将series的维度从(3,)变成(3,1)这种操作在pandas还是numpy中都是很实用的
Out:
a b c
one 1 2 3
two 7 8 9
threee 13 14 15
frame+np.broadcast_to(series,(3,3))
Out:
a b c
one 1 5 9
two 4 8 12
threee 7 11 15
我们可以看到,这种得到的结果就是我们想要的了。