1

我有一个pandas看起来像的 DataFrameY =

       0  1  2  3
0      1  1  0  0
1      0  0  0  0
2      1  1  1  0
3      1  1  0  0
4      1  1  0  0
5      1  1  0  0
6      1  0  0  0
7      1  1  1  0
8      1  0  0  0
...   .. .. .. ..
14989  1  1  1  1
14990  1  1  1  0
14991  1  1  1  1
14992  1  1  1  0

[14993 rows x 4 columns]

共有 5 个唯一值:

1  1  0  0
0  0  0  0
1  1  1  0
1  0  0  0
1  1  1  1

对于每个唯一值,我想计算它在Y DataFrame

4

3 回答 3

3

让我们使用np.unique

c,v=np.unique(df.values,axis=0,return_counts =True)
c
array([[0, 0, 0, 0],
       [1, 0, 0, 0],
       [1, 1, 0, 0],
       [1, 1, 1, 0]], dtype=int64)
v
array([1, 2, 4, 2], dtype=int64)
于 2019-03-10T22:08:40.650 回答
3

我们可以使用.groupby它来获得唯一的组合。在应用 groupby 时,我们计算size聚合的。

# Groupby on all columns which aggregates the data
df_group = df.groupby(list(df.columns)).size().reset_index()

# Because we used reset_index we need to rename our count column
df_group.rename({0:'count'}, inplace=True, axis=1)

输出

   0  1  2  3  count
0  0  0  0  0      1
1  1  0  0  0      2
2  1  1  0  0      4
3  1  1  1  0      4
4  1  1  1  1      2

笔记

我复制了您提供的示例数据框。看起来像这样:

print(df)
       0  1  2  3
0      1  1  0  0
1      0  0  0  0
2      1  1  1  0
3      1  1  0  0
4      1  1  0  0
5      1  1  0  0
6      1  0  0  0
7      1  1  1  0
8      1  0  0  0
14989  1  1  1  1
14990  1  1  1  0
14991  1  1  1  1
14992  1  1  1  0
于 2019-03-10T21:00:20.420 回答
1

我为你做了样品。


    import itertools
    import random
    iter_list  = list(itertools.product([0,1],[0,1],[0,1],[0,1]))
    sum_list = []
    for i in range(1000):
        sum_list.append(random.choice(iter_list))

    target_df = pd.DataFrame(sum_list)
    target_df.reset_index().groupby(list(target_df.columns)).count().rename(columns ={'index':'count'}).reset_index()

于 2019-03-11T01:17:38.710 回答