对多列中具有相同值的数据进行计数和分组
Counting and grouping data that have the same value in several columns
我很难完成这个特定的任务:我想从下面的数据中计算所有度数都等于 0 的元素并将它们分组。换句话说,有多少X1的三个度数都为0?
Element | Degree A | Degree B | Degree C |
.............................................
X1 | 0 0 0
X1 | 1 1 0
X1 | 0 0 0
X2 | 1 0 1
X2 | 0 0 0
X2 | 0 0 0
X3 | 0 0 0
X3 | 1 1 0
X3 | 0 1 0
这是期望的输出:
Element All=0 counts
................................
X1 2
X2 2
X3 1
这是我试过的:
d1 = df.groupby(["Element"])["Degree A"].apply(lambda x: (x==0).sum())
我尝试添加其他列,但它不起作用
d2 = df.groupby(["Element"])["Degree A"]&["Degree B"]&["Degree C"].apply(lambda x: (x==0).sum())
一个合理的方法是在 groupby 之前创建另一列:
df['check'] = df['Degree A'] + df["Degree B"] + df['Degree C'] == 0
df.groupby(['Element'])['check'].sum()
这给出了所需的输出。
您可以对类似 'Degree' 的列求和,并使用 filter
+ sum(axis=1)
+ eq(0)
检查它们的结果是否等于 0。这导致 boolean
series
可以传递到 loc
中,这将 return 仅包含总和为 0 的行的数据帧。
在此结果中,您可以使用 groupby.size()
来计算每个元素的出现次数:
df.loc[df.filter(like='Degree').sum(1).eq(0)]\
.groupby('Element', as_index=False).size()
Element size
0 X1 2
1 X2 2
2 X3 1
数据样本:
df = pd.DataFrame(
{'Element': {0: 'X1',
1: 'X1',
2: 'X1',
3: 'X2',
4: 'X2',
5: 'X2',
6: 'X3',
7: 'X3',
8: 'X3'},
'Degree A': {0: 0, 1: 1, 2: 0, 3: 1, 4: 0, 5: 0, 6: 0, 7: 1, 8: 0},
'Degree B': {0: 0, 1: 1, 2: 0, 3: 0, 4: 0, 5: 0, 6: 0, 7: 1, 8: 1},
'Degree C': {0: 0, 1: 0, 2: 0, 3: 1, 4: 0, 5: 0, 6: 0, 7: 0, 8: 0}}
)
我很难完成这个特定的任务:我想从下面的数据中计算所有度数都等于 0 的元素并将它们分组。换句话说,有多少X1的三个度数都为0?
Element | Degree A | Degree B | Degree C |
.............................................
X1 | 0 0 0
X1 | 1 1 0
X1 | 0 0 0
X2 | 1 0 1
X2 | 0 0 0
X2 | 0 0 0
X3 | 0 0 0
X3 | 1 1 0
X3 | 0 1 0
这是期望的输出:
Element All=0 counts
................................
X1 2
X2 2
X3 1
这是我试过的:
d1 = df.groupby(["Element"])["Degree A"].apply(lambda x: (x==0).sum())
我尝试添加其他列,但它不起作用
d2 = df.groupby(["Element"])["Degree A"]&["Degree B"]&["Degree C"].apply(lambda x: (x==0).sum())
一个合理的方法是在 groupby 之前创建另一列:
df['check'] = df['Degree A'] + df["Degree B"] + df['Degree C'] == 0
df.groupby(['Element'])['check'].sum()
这给出了所需的输出。
您可以对类似 'Degree' 的列求和,并使用 filter
+ sum(axis=1)
+ eq(0)
检查它们的结果是否等于 0。这导致 boolean
series
可以传递到 loc
中,这将 return 仅包含总和为 0 的行的数据帧。
在此结果中,您可以使用 groupby.size()
来计算每个元素的出现次数:
df.loc[df.filter(like='Degree').sum(1).eq(0)]\
.groupby('Element', as_index=False).size()
Element size
0 X1 2
1 X2 2
2 X3 1
数据样本:
df = pd.DataFrame(
{'Element': {0: 'X1',
1: 'X1',
2: 'X1',
3: 'X2',
4: 'X2',
5: 'X2',
6: 'X3',
7: 'X3',
8: 'X3'},
'Degree A': {0: 0, 1: 1, 2: 0, 3: 1, 4: 0, 5: 0, 6: 0, 7: 1, 8: 0},
'Degree B': {0: 0, 1: 1, 2: 0, 3: 0, 4: 0, 5: 0, 6: 0, 7: 1, 8: 1},
'Degree C': {0: 0, 1: 0, 2: 0, 3: 1, 4: 0, 5: 0, 6: 0, 7: 0, 8: 0}}
)