Pandas Fill NA with Group Value

前端 未结 1 1878
温柔的废话
温柔的废话 2021-01-16 23:57

Given the following data frame:

import pandas as pd
import numpy as np
df = pd.DataFrame({\'Site\':[\'A\',\'A\',\'A\',\'B\',\'B\',\'B\',\'C\',\'C\',\'C\'],
          


        
1条回答
  •  长发绾君心
    2021-01-17 00:45

    You can use transform as answered here

    df['Value'] = df.groupby('Site').transform(lambda x: x.fillna(x.mean()))
    
    
      Site  Value
    0    A      1
    1    A      1
    2    A      1
    3    B      2
    4    B      2
    5    B      2
    6    C      3
    7    C      3
    8    C      3
    

    0 讨论(0)
提交回复
热议问题