待看

Pandas分组之统计个数

2021-11-25  本文已影响0人  测试探索

需求:

统计每位员工的不同分数以及对应个数

一:数据准备

employees = ["小明","小周","小孙"]   # 3位员工

df=pd.DataFrame({
    "employees":[employees[x] for x in np.random.randint(0,len(employees),9)],  # 在员工中重复选择9个人
    "salary":np.random.randint(800,1000,9),  # 800-1000之间的薪资选择9个数值
    "score":np.random.randint(6,11,9)  # 6-11的分数选择9个
})
print(df)
image.png

二:处理

df1 = df.groupby("employees").agg({"score":"unique"}).reset_index().rename(columns = {"score":"分数"})
print("df1","\n",df1)

df2 = df.groupby("employees").agg({"score":"nunique"}).reset_index().rename(columns = {"score":"分数个数"})
print("df2","\n",df2)

df_merge = pd.merge(df1,df2)
print("df_merge","\n",df_merge)
image.png
上一篇下一篇

猜你喜欢

热点阅读