(数据样本并在问题末尾尝试)
具有这样的数据框:
Type Class Area Decision
0 A 1 North Yes
1 B 1 North Yes
2 C 2 South No
3 A 3 South No
4 B 3 South No
5 C 1 South No
6 A 2 North Yes
7 B 3 South Yes
8 B 1 North No
如何将Decision
分组,并在其他列下获得Decision
的唯一值计数,所以我得出以下结论:
Decision Area_North Aread_South Class_1 Class_2 Type_A Type_B Type_C
Yes 3 1 2 0 2 2 1
No 1 4 1 1 1 2 2
我确信可以像这样使用groupby().agg()
入门,
dfg = df.groupby('Decision').agg({'Type':'count',
'Class':'count',
'Decision':'count'})
然后旋转结果,但到目前为止还远远不够。我将需要以某种方式包括所有其他列的唯一值。我确信我在这里看到过可以将'Position':'count'
替换为'Position':pd.Series.unique
的地方,但我似乎无法使其正常工作。
代码:
import pandas as pd
df = pd.DataFrame({'Type': {0: 'A',
1: 'B',
2: 'C',
3: 'A',
4: 'B',
5: 'C',
6: 'A',
7: 'B',
8: 'B'},
'Class': {0: 1, 1: 1, 2: 2, 3: 3, 4: 3, 5: 1, 6: 2, 7: 3, 8: 1},
'Area': {0: 'North',
1: 'North',
2: 'South',
3: 'South',
4: 'South',
5: 'South',
6: 'North',
7: 'South',
8: 'North'},
'Decision': {0: 'Yes',
1: 'Yes',
2: 'No',
3: 'No',
4: 'No',
5: 'No',
6: 'Yes',
7: 'Yes',
8: 'No'}})
dfg = df.groupby('Decision').agg({'Type':'count',
'Class':'count',
'Decision':'count'})
dfg
答案 0 :(得分:4)
将DataFrame.melt
与DataFrame.pivot_table
结合使用并展平MultiIndex
:
df = df.melt('Decision').pivot_table(index='Decision',
columns=['variable','value'],
aggfunc='size',
fill_value=0)
df.columns = df.columns.map('{0[0]}_{0[1]}'.format)
df = df.reset_index()
print (df)
Decision Area_North Area_South Class_1 Class_2 Class_3 Type_A Type_B \
0 No 1 4 2 1 2 1 2
1 Yes 3 1 2 1 1 2 2
Type_C
0 2
1 0
答案 1 :(得分:2)
groupby
与value_counts
+ s=df.melt('Decision').groupby(['Decision','variable']).\
value.value_counts().unstack(level=[1,2],fill_value=0)
variable Area Class Type
value South North 1 3 2 B C A
Decision
No 4 1 2 2 1 2 2 1
Yes 1 3 2 1 1 2 0 2
s.columns = s.columns.map('{0[0]}_{0[1]}'.format)
您还可以通过
修改以上列$text_count = Text::whereBetween('created_at', [$date1, $date2])->count();