1 回答

TA貢獻1828條經驗 獲得超6個贊
第一個選項 ( s1.reindex_like(s2).fillna(method='ffill')) 首先進行重新索引,留下空 ( NaN) 值,然后填充它們。
reindex_like回報 [1] :
s1.reindex_like(s2)
6 [6,inf)
2 NaN
5 NaN
0 [0,1)
4 [4,6)
7 NaN
1 [1,3)
3 [3,4)
dtype: object
現在,您看到fillna(method='ffill')它按系列的順序向前填充,因為它在此處排序(即它沿著未排序的索引“向前”)。
相反,第二個選項 ( s1.reindex_like(s2, method='ffill')) 在排序的索引中進行前向填充。
您可以通過將此結果(在對其索引進行排序之后)與首先對 s2 的索引進行排序的結果進行比較來驗證此聲明:
s_when_sort_s2_before = s1.reindex_like(s2.sort_index()).fillna(method='ffill')
s_sorted_after = s1.reindex_like(s2, method='ffill').sort_index()
pd.testing.assert_series_equal(s_when_sort_s2_before, s_sorted_after)
這個斷言什么都不做(即不引發AssertionError),因為兩者確實相等。
[1] 你可以通過我dtype: object知道我和你不是同一個 pandas 版本,但我可以重現這個問題,所以我認為這個解決方案是可行的——在你這邊驗證一下。
添加回答
舉報