ID a b c d e f g
a 1 2 3 4 5 2 2
b 2 3 5 3 4 3 5
c 2 3 4 2 4 2 4
a 2 3 4 2 5 2 5
a 0 0 2 4 2 4 2
c 2 4 2 4 4 2 4
the goal is to create 4 new column based on c,d,e,f
new_c = df.groupby('ID')['c'].transform('mean')
new_d = df.groupby('ID')['d'].transform('mean')
new_e = df.groupby('ID')['e'].transform('mean')
new_f = df.groupby('ID')['f'].transform('mean')
My code looks like below, but it doesn't allow me to use group by. Also, I want to append the new columns to the original df. Is there anyway to fix my code?
for col in df[2:-2]:
res = df.groupby('ID')(df[col]).transform('mean')
return res
question from:
https://stackoverflow.com/questions/66051485/easier-way-to-fix-pandas 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…