pandas 两列组成字典格式;map使用;修改某一列的格式;agg聚合函数;assign函数

1、两列组成字典格式

df[["a", "b"]].set_index("a").to_dict()["b"]

2、map支持

Series.map(function)

#DataFrame中的一列是Series数据类型。data['label'] = data['营业收入'].map(lambda x:1 if x >25000 else 0)
data

Series.map(dict)

data['label'] = data['label'].map({1:'高收入',0:'低收入'})
data

3、修改某一列的格式

df.longitude = df.longitude.astype(float).fillna(0.0)

4、多函数计算:agg()

概念:聚合函数、开窗函数、分组功能

聚合函数

操作行数据,进行合并
sum、avg、count、max、min


开窗函数

将合并的数据分布到原表的每一行,相当于多出来了一列,这一列可能是sum求和的数、或者avg平均数的值
也可以与排名函数一起使用

分组功能

对某一列进行分组,也就是对数据进行压缩
分组关键字经常与聚合函数搭配使用,计算每一组的合并后的数值
group by 之后如果是多个,标识的多个列的值一样的分成一个组

函数写法可以用str,或者np.方法

可以通过list,dict传入,当用dict时,key名为columns

df = pd.DataFrame({‘a’:[1,1,2,2],
‘b’:np.random.rand(4),
‘c’:np.random.rand(4),
‘d’:np.random.rand(4),})
‘’’
a b c d
0 1 0.357911 0.318324 0.627797
1 1 0.964829 0.500017 0.570063
2 2 0.116608 0.194164 0.049509
3 2 0.933123 0.542615 0.718640
‘’’

print(df.groupby(‘a’).agg([‘mean’,np.sum]))
‘’’
b c d
mean sum mean sum mean sum
a
1 0.661370 1.322739 0.409171 0.818341 0.598930 1.19786
2 0.524865 1.049730 0.368390 0.736780 0.384075 0.76815
‘’’

print(df.groupby(‘a’)[‘b’].agg({‘result1’:np.mean,
‘result2’:np.sum}))
‘’’
result2 result1
a
1 1.322739 0.661370
2 1.049730 0.524865
‘’’

5、assign函数

与apply类似,就是不改变原来数据
参考:https://zhuanlan.zhihu.com/p/412470486
在这里插入图片描述

Guess you like

Origin blog.csdn.net/weixin_42357472/article/details/120157775