我的数据集如下
Month DayOfWeek Class A1 A2 ... A999
July Monday Bata 7 9 ... 5
July Tuesay Bata 3 1 ... 2
July Sunday Bata 4 5 ... 6
July Monday Adid 9 8 ... 5
July Sunday Adid 4 0 ... 4
Sept Monday Nike 7 5 ... 7
Sept Sunday Nike 8 3 ... 7
Sept Satday Adid 2 7 ... 7
Sept Monday Bata 8 9 ... 4
Oct Monday Nike 4 2 ... 5
Oct Sunday Bata 8 6 ... 3
July Monday Nike NaN NaN NaN
Sept Sunday Nike NaN NaN NaN
Oct Satday Nike NaN NaN NaN
Sept Monday Bata NaN NaN NaN
我想用先前记录的平均值填充 NaNs
我知道我可以使用
df['A1'] = df['A1'].fillna((df['A1'].mean()))
但这是一种不好的方法,因为我有1000多个列,以后它们可能会增加
添加到
我想根据Month和DayOfWeek找到平均值
为此记录
July Monday Nike NaN NaN NaN
因此,平均值将仅是具有 Month = July&DayOfWeek = Monday
的记录的平均值。我该怎么做?
答案 0 :(得分:1)
您在这里:
df['A1'] = df.groupby(['Month','DayOfWeek'])['A1'].transform(lambda x: x.fillna(x.mean()))
以上内容仍将提供一个空值,因为没有“ Month = Oct&DayOfWeek = Monday”的值。 在这种情况下,您可能需要编写第二个代码来填充该月的平均值或DayOfWeek的平均值。 下面的代码段用空值填充记录月份的平均值:
df['A1'] = df.groupby('Month')['A1'].transform(lambda x: x.fillna(x.mean()))
如果有帮助,请投票