为什么reindex_like(s,method ='ffill')与reindex_like(s).fillna(method ='ffill')

问题描述 投票:1回答:1

我正在尝试使用另一个序列的索引来重新索引一个序列并填充缺失的值。

具有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')
>>>
>>> s1
0      [0, 1)
1      [1, 3)
3      [3, 4)
4      [4, 6)
6    [6, inf)
dtype: string
>>> s2
6    
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

我对两种方法都期望得到相同的结果,为什么它们的行为有所不同?

python pandas
1个回答
1
投票

第一个选项(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告知我与您使用的熊猫版本不同,但是我可以重现该问题,因此我认为解决方案是可行的-请在您端进行验证。

© www.soinside.com 2019 - 2024. All rights reserved.