我有一个数据帧:
df =
ID WorkAddress City Lat Long Department
1 0001 123_lane City1 17.4 78.3 Audit
2 0002 123_lane City1 17.4 78.3 Lending
3 0003 111_lane City2 19.6 64.2 Finance
4 0004 112_lane City3 18.4 89.9 Legal
5 0005 112_lane City3 18.4 89.9 Legal
我将其转换为按不同的工作地址对每个部门的每个ID进行计数:
dfDeptCounts = df.assign(flag=df.groupby('WorkAddress').Department.cumcount())\
.pivot_table(index='WorkAddress', columns=['Department'], values='ID', aggfunc='count').reset_index()
dfDeptCounts =
WorkAddress Audit Lending Finance Legal
1 123_lane 1 1 0 0
2 111_lane 0 0 1 0
3 112_lane 0 0 0 2
我试图包含City、Lat、Long的任何操作都会导致错误,无论是将其作为附加groupby添加,还是尝试重置索引。是否有我缺少的多索引级别,或者是否有更好的方法将df转换为包含所有列
很抱歉,我的问题可能不太清楚。这是最终目标:
dfDeptCounts =
WorkAddress City Lat Long Audit Lending Finance Legal
1 123_lane City1 17.4 78.3 1 1 0 0
2 111_lane City2 19.6 64.2 0 0 1 0
3 112_lane City3 18.4 89.9 0 0 0 2
将@Psidom的回答作为一个注释进行一点扩展。可以将^{} 与categorical data结合使用:
分类数据的使用将确保在最终的交叉表中,即使是缺少的或空的类别(此处为“HR”)也会被表示出来。为此,您需要添加
dropna=False
参数输出:
现在,如果要添加其他信息,首先需要选择要删除的行(此处不重要,因为信息相同,所以我们保留第一行),然后将其与以前的输出合并:
输出:
相关问题 更多 >
编程相关推荐