我有以下数据帧:
name state teams score
abc NY red 1
def VA yellow 9
ghi MO green 6
abc WA red 2
klm IL yellow 1
ghi MN green 8
def VA blue 3
xyz NY blue 5
abc NY blue 5
abc NY red 4
ghi MN green 7
我想以这样的方式对每个名称状态组合的数据进行分组,我希望每个团队的得分最低,例如,在我们拥有的数据中:名称'abc',状态'NY‘和团队'red’有两个得分1和4,那么在这里,团队'red‘的最低得分是1。
对于我们没有得分的球队,最小的得分可以是0。
输出示例:
name state red yellow green blue
abc NY 1 0 0 5
def VA 0 9 0 3
ghi MO 0 0 6 0
abc WA ....................
klm IL ....................
ghi MN 0 0 7 0
xyz NY 0 0 0 5
发布于 2018-06-06 05:27:34
选项1:使用groupby
和unstack
使用,first
获取一个值,并使用unstack
中的fill_value
参数将NaN替换为零:
df.groupby(['name','state','teams']).min()['score'].unstack(fill_value=0).reset_index()
输出:
teams name state blue green red yellow
0 abc NY 5 0 1 0
1 abc WA 0 0 2 0
2 def VA 3 0 0 9
3 ghi MN 0 8 0 0
4 ghi MO 0 6 0 0
5 klm IL 0 0 0 1
6 xyz NY 5 0 0 0
选项2:使用pd.crosstab
(pd.crosstab([df['name'],df['state']],df['teams'],df['score'],aggfunc='min')\
.fillna(0)
.astype(int)
.reset_index())
选项3:使用pd.pivot_table
(pd.pivot_table(df,'score',['name','state'],'teams',aggfunc='min', fill_value=0)
.reset_index())
https://stackoverflow.com/questions/50709114
复制相似问题