Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
894 views
in Technique[技术] by (71.8m points)

python - Inplace transformation pandas with groupby

Would it be possible to mutate DataFrame inplace with groupby statement?

import pandas as pd
dt = pd.DataFrame({
                   "LETTER": ["a", "b", "c", "a", "b"],
                   "VALUE" : [10 , 12 , 13,  0,  15]
                   })
def __add_new_col(dt_):
    dt_['NEW_COL'] = dt_['VALUE'] - dt_['VALUE'].mean()
    return dt_
pass


dt.groupby("LETTER").apply(__add_new_col)
  LETTER  VALUE  NEW_COL
0      a     10      5.0
1      b     12     -1.5
2      c     13      0.0
3      a      0     -5.0
4      b     15      1.5


dt
  LETTER  VALUE
0      a     10
1      b     12
2      c     13
3      a      0
4      b     15

In R data.table it is possible by using := operator e.g. dt[, col := ... , by ='LETTER']

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

I think you can use transform which return Series same length and same index as df with substracting:

print (dt.groupby("LETTER")['VALUE'].transform('mean'))
0     5.0
1    13.5
2    13.0
3     5.0
4    13.5
Name: VALUE, dtype: float64

dt['NEW_COL'] = dt['VALUE'] - dt.groupby("LETTER")['VALUE'].transform('mean')
print (dt)
  LETTER  VALUE  NEW_COL
0      a     10      5.0
1      b     12     -1.5
2      c     13      0.0
3      a      0     -5.0
4      b     15      1.5

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...