如何用分组的方式填充熊猫的na



我有一个Pandas数据帧,如下所示:

df = 
a                    b
a1                   b1
a1                   b2
a1                   b1
a1                   Nan
a2                   b1
a2                   b2
a2                   b2
a2                   Nan
a2                   b2
a3                   Nan

对于a的每个值,b可以有多个对应的b值。我想用a的对应值分组的b值的模式来填充b的所有nan值。

生成的数据帧应该如下所示:

df = 
a                    b
a1                   b1
a1                   b2
a1                   b1
a1                   ***b1***
a2                   b1
a2                   b2
a2                   b2
a2                   **b2**
a2                   b2
a3                   b2

在CCD_ 8之上是对应于CCD_ 10的CCD_ 9的模式。类似地,b2是对应于a2的模式。最后,a3没有数据,所以它用全局模式b2填充它。

对于b列的每个nan值,我想用b列的值的模式填充它,但是,对于a的特定值,不管模式是什么。

编辑:

如果有一个组ab上没有数据,则用全局模式填充。

尝试:

# lazy grouping
groups = df.groupby('a')
# where all the rows within a group is NaN
all_na = groups['b'].transform(lambda x: x.isna().all())
# fill global mode
df.loc[all_na, 'b'] = df['b'].mode()[0]
# fill with local mode
mode_by_group = groups['b'].transform(lambda x: x.mode()[0])
df['b'] = df['b'].fillna(mod_by_group)

You are getting the IndexError: index out of bounds because last a column value a3没有相应的b列值。因此,没有需要填补的小组。Solution would be have try catch block while fillna and then apply ffill and bfill。这是代码解决方案。

data_stack = [['a1','b1'],['a1','b2'],['a1','b1'],['a1',np.nan],['a2','b1'], 
['a2','b2'],['a2','b2'],['a2',np.nan],['a2','b2'],['a3',np.nan]]
df_try_stack = pd.DataFrame(data_stack, columns=["a","b"])
# This function will fill na values of group to the mode value
def fillna_group(grp):
try:
return grp.fillna(grp.mode()[0])
except BaseException as e:
print('Error as no correspindg group: ' + str(e))
df_try_stack["b"] = df_try_stack["b"].fillna(df_try_stack.groupby(["a"]) 
['b'].transform(lambda grp : fillna_group(grp)))
df_try_stack = df_try_stack.ffill(axis = 0)
df_try_stack = df_try_stack.bfill(axis =0)

最新更新