亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

為什么 reindex_like(s, method='ffill') 不同于

為什么 reindex_like(s, method='ffill') 不同于

慕少森 2022-12-20 16:27:21
我正在嘗試使用另一個系列的索引重新索引一個系列并填充缺失值。pandas版本 1.0.3的演示:>>> import pandas as pd>>> s1 = pd.Series(['[0, 1)', '[1, 3)', '[3, 4)', '[4, 6)', '[6, inf)'], index=[0, 1, 3, 4, 6], dtype='string')>>> s2 = pd.Series(['']*8, index=[6, 2, 5, 0, 4, 7, 1, 3], dtype='string')>>>>>> s10      [0, 1)1      [1, 3)3      [3, 4)4      [4, 6)6    [6, inf)dtype: string>>> s26    2    5    0    4    7    1    3    dtype: string>>> s1.reindex_like(s2).fillna(method='ffill')6    [6, inf)2    [6, inf)5    [6, inf)0      [0, 1)4      [4, 6)7      [4, 6)1      [1, 3)3      [3, 4)dtype: string>>> s1.reindex_like(s2, method='ffill')6    [6, inf)2      [1, 3)5      [4, 6)0      [0, 1)4      [4, 6)7    [6, inf)1      [1, 3)3      [3, 4)dtype: string我期望這兩種方法的結果相同,為什么它們的行為不同?
查看完整描述

1 回答

?
30秒到達戰場

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 版本,但我可以重現這個問題,所以我認為這個解決方案是可行的——在你這邊驗證一下。


查看完整回答
反對 回復 2022-12-20
  • 1 回答
  • 0 關注
  • 120 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號