![](/img/trans.png)
[英]Pandas dataframe, how can I group by multiple columns and apply sum for specific column and add new count column?
[英]How to group by certain column then take the count of multiple columns where it is not NA and add them in Pandas Python?
我想按 ID 分組,然后添加 A 和 B 中不是 NA 的值的計數,然后將 A 和 B 的計數加在一起。 除此之外,如果我只想計算 A 中的 y 值怎么辦?
+----+---+---+
| ID | A | B |
+----+---+---+
| 1 | x | x |
| 1 | x | x |
| 1 | y | |
| 2 | y | x |
| 2 | y | |
| 2 | y | x |
| 2 | x | x |
| 3 | x | x |
| 3 | | x |
| 3 | y | x |
+----+---+---+
+----+--------+
| ID | Output |
+----+--------+
| 1 | 3 |
| 2 | 6 |
| 3 | 4 |
+----+--------+
這是一種方法:
df = df.groupby('ID').agg(lambda x: sum(pd.notna(x))).sum(1).reset_index(name='Output')
print(df)
ID Output
0 1 5.0
1 2 7.0
2 3 5.0
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.