Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/joomla/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Pandas (熊猫)为什么.bfill().ffill()在组上的行为与ffill().bfill()不同?_Pandas_Group By_Pandas Groupby - Fatal编程技术网

Pandas (熊猫)为什么.bfill().ffill()在组上的行为与ffill().bfill()不同?

Pandas (熊猫)为什么.bfill().ffill()在组上的行为与ffill().bfill()不同?,pandas,group-by,pandas-groupby,Pandas,Group By,Pandas Groupby,我想我在概念上遗漏了一些基本的东西,但我无法在文档中找到答案 >>> df=pd.DataFrame({'a':[1,1,2,2,3,3], 'b':[5,np.nan, 6, np.nan, np.nan, np.nan]}) >>> df a b 0 1 5.0 1 1 NaN 2 2 6.0 3 2 NaN 4 3 NaN 5 3 NaN 使用ffill()和bfill(): 使用bfill()和ffill(): 第

我想我在概念上遗漏了一些基本的东西,但我无法在文档中找到答案

>>> df=pd.DataFrame({'a':[1,1,2,2,3,3], 'b':[5,np.nan, 6, np.nan, np.nan, np.nan]})
>>> df
   a    b
0  1  5.0
1  1  NaN
2  2  6.0
3  2  NaN
4  3  NaN
5  3  NaN
使用ffill()和bfill():

使用bfill()和ffill():

第二条路不是打破了分组吗?第一种方法是否始终确保仅使用该组中的其他值填写值?

我认为您需要:

print (df.groupby('a')['b'].apply(lambda x: x.ffill().bfill()))
0    5.0
1    5.0
2    6.0
3    6.0
4    NaN
5    NaN
Name: b, dtype: float64

print (df.groupby('a')['b'].apply(lambda x: x.bfill().ffill()))
0    5.0
1    5.0
2    6.0
3    6.0
4    NaN
5    NaN
Name: b, dtype: float64
因为在您的示例中,只有第一个
ffill
bfill
是或,第二个是处理输出
系列
。所以它将分组,因为
系列
没有分组

print (df.groupby('a')['b'].ffill())
0    5.0
1    5.0
2    6.0
3    6.0
4    NaN
5    NaN
Name: b, dtype: float64

print (df.groupby('a')['b'].bfill())
0    5.0
1    NaN
2    6.0
3    NaN
4    NaN
5    NaN
Name: b, dtype: float64
print (df.groupby('a')['b'].apply(lambda x: x.ffill().bfill()))
0    5.0
1    5.0
2    6.0
3    6.0
4    NaN
5    NaN
Name: b, dtype: float64

print (df.groupby('a')['b'].apply(lambda x: x.bfill().ffill()))
0    5.0
1    5.0
2    6.0
3    6.0
4    NaN
5    NaN
Name: b, dtype: float64
print (df.groupby('a')['b'].ffill())
0    5.0
1    5.0
2    6.0
3    6.0
4    NaN
5    NaN
Name: b, dtype: float64

print (df.groupby('a')['b'].bfill())
0    5.0
1    NaN
2    6.0
3    NaN
4    NaN
5    NaN
Name: b, dtype: float64