ts = pd.Series({'a' : 1, 'b' : 2})
ids = ['a','c'] # 'c' is not in the index
# the result I want
np.array([ts.get(k, np.nan) for k in ids])
有没有Pandas 本土的方法来实现这一目标?
ts = pd.Series({'a' : 1, 'b' : 2})
ids = ['a','c'] # 'c' is not in the index
# the result I want
np.array([ts.get(k, np.nan) for k in ids])
有没有Pandas 本土的方法来实现这一目标?
reindex
并访问底层numpy数组:
out = ts.reindex(ids).values
# or
# out = ts.reindex(ids).to_numpy()
输出:array([ 1., nan])
请注意,reindex
中的fill_value
默认为NaN,如果需要,您可以更改它:
ts.reindex(ids, fill_value=0).values
# array([1, 0])