我正在研究“用于数据分析的 Python”,但我不了解特定功能。添加两个 pandas 系列对象将自动对齐索引数据,但如果一个对象不包含该索引,则返回为 NaN。例如从书中:
a = Series([35000,71000,16000,5000],index=['Ohio','Texas','Oregon','Utah'])
b = Series([NaN,71000,16000,35000],index=['California', 'Texas', 'Oregon', 'Ohio'])
结果:
In [63]: a
Out[63]: Ohio 35000
Texas 71000
Oregon 16000
Utah 5000
In [64]: b
Out[64]: California NaN
Texas 71000
Oregon 16000
Ohio 35000
当我把它们加在一起时,我得到了这个......
In [65]: a+b
Out[65]: California NaN
Ohio 70000
Oregon 32000
Texas 142000
Utah NaN
那么为什么犹他州的值是 NaN 而不是 500?似乎 500+NaN=500。是什么赋予了?我遗漏了一些东西,请解释一下。
更新:
In [92]: # fill NaN with zero
b = b.fillna(0)
b
Out[92]: California 0
Texas 71000
Oregon 16000
Ohio 35000
In [93]: a
Out[93]: Ohio 35000
Texas 71000
Oregon 16000
Utah 5000
In [94]: # a is still good
a+b
Out[94]: California NaN
Ohio 70000
Oregon 32000
Texas 142000
Utah NaN