单列计算

  1. df['col2'] = df['col1'].map(lambda x: x**2)
  2. # 自定义lambda函数
  3. define square(x):
  4. return (x ** 2)
  5. df['col2'] = df['col1'].map(square)

多列计算

  1. # 必须设置axis=1进行列操作
  2. df['col3'] = df.apply(lambda x: x['col1'] + 2 * x['col2'], axis=1)

分组计算

  1. df['col3'] = df.groupby('col1')['col2'].transform(lambda x: (x.sum() - x) / x.count())
  2. # 或
  3. sumcount = df.groupby('col1')['col2'].transform(lambda x: x.sum() + x.count())
  4. df['col3'].map(sumcount)

聚合函数

  1. df['col2'] = df.groupby('col1').agg({'col1':{'col1_mean': mean, 'col1_sum‘’: sum}, 'col2': {'col2_count': count}})