Pandas计数一列中的实例数,并根据另一列进行分组

时间:2019-10-04 05:30:33

标签: pandas

我想在我的数据框上使用熊猫查询,以计算“天数”列中0的次数,而不是“ SUPPLY_CNT”和“ byid”列中的null。

Example Dataframe

   ID   |  Days | SUPPLY_CNT |
-----------------------------|
| 1561  |  -11  |     15     |
| 1561  |    0  |     05     |
| 1561  |   44  |     11     |
| 1561  |    0  |            |
| 1561  |    0  |     24     |
| 1561  |   56  |     24     |
| 1561  |    0  |     19     |
| 1561  |   92  |     21     |
| 2412  |  -789 |     09     |
| 2412  |  -456 |     09     |
| 2412  |  -321 |     31     |
| 2412  |    0  |            |
| 2412  |   99  |     32     |
| 2412  |    0  |     14     |
| 2412  |    0  |     18     |
| 7848  |   451 |     11     |
| 7848  |   3222|     21     |
| 7848  |    0  |     12     |
------------------------------

Expected Output:

1561     3
2412     2
7848     1

我有此查询,但需要按“ id”进行分组

(df.loc[(df['Days'] == 0) & (df['PAY_DAY_SUPPLY_CNT'].notnull())])
R Equivalent:

  filter(Days==0 & !is.na(PAY_DAY_SUPPLY_CNT))%>%
  group_by(id)%>%
  count(Days)%>%
  arrange(desc(n))

3 个答案:

答案 0 :(得分:1)

为测试0的值创建掩码并且不丢失,并将其转换为integer s:

m = ((df['Days'] == 0) & df['SUPPLY_CNT'].notna()).astype(int)

对于计数总计sum

df1 = m.groupby(df['ID']).sum().reset_index(name='count')
print (df1)

     ID  count
0  1561      3
1  2412      2
2  7848      1

对于Series

s = m.groupby(df['ID']).sum()
print (s)
ID
1561    3
2412    2
7848    1
dtype: int32

答案 1 :(得分:0)

在这里,我们首先获取true值为falseToolbar toolbar = (Toolbar) findViewById(R.id.toolbar); setSupportActionBar(toolbar); 是一个数字的行。然后我们对此进行分组。

Days

输出

0

答案 2 :(得分:0)

我认为这会帮助您。

struct RowView: View {
    var body: some View {
        Rectangle()
            .foregroundColor(.blue)
            .frame(height: 150)
            .cornerRadius(10)
    }
}

struct ListView: View {
    var body: some View {
        // you won't get the width of the container if you embed this view inside a horizontal scroll view which is the case for you
        // so you have to impose the explicit width from the parent view
        ScrollView(.vertical) {
            VStack(spacing: 16) {
                RowView()
                RowView()
                RowView()
            }
            .padding()
        }
    }
}

struct ContentView: View {
    var body: some View {
        GeometryReader { geometry in
            ScrollView(.horizontal) {
                HStack {
                    // you have to be explicit about the width of each content of the scroll view as it can't determine width of each content by itself
                    ListView().frame(width: geometry.size.width)
                    ListView().frame(width: geometry.size.width)
                    ListView().frame(width: geometry.size.width)
                }
            }
        }
    }
}