单列运算
在Pandas中,DataFrame的一列就是一个Series, 可以通过map来对一列进行操作:
df['new_col'] = df['col1'].map(lambda x: x**2)
多列运算
要对DataFrame的多个列同时进行运算,可以使用apply,例如new_col= col1 + col2:
df['new_col'] = df.apply(lambda x: x['col1'] + x['col2'], axis=1)
分组运算
可以结合groupby与transform来方便地实现类似SQL中的聚合运算的操作:
df['new_col'] = df.groupby('col1')['col2'].transform(lambda x: (x.sum() - x) / x.count())
在transform函数中x.sum()与x.count()与SQL类似,计算的是当前group中的和与数量,还可以将transform的结果作为一个一个映射来使用, 例如:
sumcount = df.groupby('col1')['col2'].transform(lambda x: x.sum() + x.count())
df['col1'].map(sumcount)
对col1进行一个map,得到对应的col2的运算值
聚合函数
结合groupby与agg实现SQL中的分组聚合运算操作,需要使用相应的聚合函数:
df['col2'] = df.groupby('col1').agg({'col1':{'col1_mean': mean, 'col1_sum‘’: sum}, 'col2': {'col2_count': count}})
上述代码生成了col1_mean, col1_sum与col2_count列。