我的原始数据看起来像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]})
答案 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