簡體   English   中英

如何按特定列分組然后計算不是 NA 的多列的計數並將它們添加到 Pandas Python 中?

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM