Pandas groupby&在保留原始列的同时转置数据帧

2024-09-28 01:28:29 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个数据帧:

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

Tags: idcitydfauditlongdepartmentlatfinance
1条回答
网友
1楼 · 发布于 2024-09-28 01:28:29

将@Psidom的回答作为一个注释进行一点扩展。可以将^{}categorical data结合使用:

df['Department'] = pd.Categorical(df['Department'],
                                  categories=['Audit', 'Lending', 'Finance',
                                              'HR', 'Legal']
                                  )
df2 = pd.crosstab(df.WorkAddress, df.Department, dropna=False)

分类数据的使用将确保在最终的交叉表中,即使是缺少的或空的类别(此处为“HR”)也会被表示出来。为此,您需要添加dropna=False参数

输出:

>>> df2
Department   Audit  Lending  Finance  HR  Legal
WorkAddress                                    
111_lane         0        0        1   0      0
112_lane         0        0        0   0      2
123_lane         1        1        0   0      0

现在,如果要添加其他信息,首先需要选择要删除的行(此处不重要,因为信息相同,所以我们保留第一行),然后将其与以前的输出合并:

(df.drop_duplicates(subset=['WorkAddress'])
   .drop('ID', axis=1)
   .merge(df2,
          left_on='WorkAddress',
          right_index=True)
)

输出:

  WorkAddress   City   Lat  Long Department  Audit  Lending  Finance  HR  Legal
1    123_lane  City1  17.4  78.3      Audit      1        1        0   0      0
3    111_lane  City2  19.6  64.2    Finance      0        0        1   0      0
4    112_lane  City2  18.4  89.9      Legal      0        0        0   0      2

相关问题 更多 >

    热门问题