1. 程式人生 > >pandas DataFrame(5)-合並DataFrame與Series

pandas DataFrame(5)-合並DataFrame與Series

得到 pan div bsp afr ram 向量 pre nbsp

之前已經學過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

pandas DataFrame(5)-合並DataFrame與Series