在列、客户和站点中有一些缺失的行。代码可以将相同的值复制到丢失的单元格中,直到另一个单元格有相同值为止。
与我的示例中的例子一样,Customer和site有5个条目,其他列有15个条目,因此代码能够在col客户和站点上填充其他丢失的值,以供参考。
import pandas as pd
df= pd.DataFrame()
df.reindex(df.index.repeat(df.a))
输出在红色中是这样的。
发布于 2022-08-30 15:44:21
我包括了一些边缘病例,因为不确定你到底想要什么:
df = pd.DataFrame({
'Customer': ['Sony', 'Samsung', 'Nokia'] + [None]*2 + [None]*4 + ['LG', 'Ford'] + [None]*3,
'site': ['s1', 's2', 's3'] + [None]*2 + [None]*4 + ['s4', 's5'] + [None]*3,
'a': ['xy']*3 + ['abc']*2 + ['xyw']*4 + ['rty']*2 + ['zxc']*3,
})
Customer site a
0 Sony s1 xy
1 Samsung s2 xy
2 Nokia s3 xy
3 None None abc
4 None None abc
5 None None xyw
6 None None xyw
7 None None xyw
8 None None xyw
9 LG s4 rty
10 Ford s5 rty
11 None None zxc
12 None None zxc
13 None None zxc
我的方法是按组(在示例中为a
列)索引数据,并在每个组中索引row_number。然后,您可以通过选择“使用索引”来获得要填充的值。
首先,让我们添加一些助手列并添加索引:
import numpy as np
df['rn'] = df.groupby('a').cumcount()+1
df['a_filled'] = pd.Series(np.where(df.Customer.isnull(), None, df.a)).fillna(method='ffill')
df2 = df.set_index(['a','rn'], drop=False)
a_filled
显示要从哪个组获取值以填充缺少的行。
现在,对于每个缺失的行,我们可以引用要填充的正确值:
fill_cols = ['Customer', 'site']
cond = lambda x: x.Customer.isnull()
df2.loc[cond, fill_cols] = df2.loc[cond].apply(lambda x: df2.loc[(x.a_filled, x.rn), fill_cols] if (x.a_filled, x.rn) in df2.index else None, axis=1)
Customer site a rn a_filled
a rn
xy 1 Sony s1 xy 1 xy
2 Samsung s2 xy 2 xy
3 Nokia s3 xy 3 xy
abc 1 Sony s1 abc 1 xy
2 Samsung s2 abc 2 xy
xyw 1 Sony s1 xyw 1 xy
2 Samsung s2 xyw 2 xy
3 Nokia s3 xyw 3 xy
4 None None xyw 4 xy
rty 1 LG s4 rty 1 rty
2 Ford s5 rty 2 rty
zxc 1 LG s4 zxc 1 rty
2 Ford s5 zxc 2 rty
3 None None zxc 3 rty
添加if (x.a_filled, x.rn) in df2.index
是为了避免使用来自较小组的值填充更大组时的KeyError。
https://stackoverflow.com/questions/73539264
复制相似问题