不同级别的熊猫计数

时间:2018-07-23 03:20:22

标签: python pandas

我的原始数据看起来像df,如何将df转换为df1?

df = pd.DataFrame({"A":["A","A","B","B","B"],
                   "B":["N","N","N","S","S"],
                   "C":["E","E","NE","NE","NE"],
                   "D":["y","n","n","y","n"]})

df1 = pd.DataFrame({"A":["A","N","E"],
                    "B":["N","N","S"],
                    "C":[2,1,2],
                    "D":[1,0,1]})

1 个答案:

答案 0 :(得分:2)

IIUC(我想df1中的第一列A为['A','B','B']

df.groupby(['A','B']).agg({'C':'count','D':lambda x : sum(x=='y')}).reset_index()
Out[285]: 
   A  B  C  D
0  A  N  2  1
1  B  N  1  0
2  B  S  2  1