在Pandas DataFrame中调用groupby对象时出错

问题描述 投票:0回答:1

我有这个数据帧:

    person_code  #CNAE   growth   size 
0           231     32     0.54     32
1           233     43     0.12    333
2           432     32     0.44     21
3           431     56     0.32     23
4           654     89     0.12     89
5           764     32     0.20    211
6           434     32     0.82     90

我需要创建一个名为“top3growth”的新列。为此,我需要检查每行的df的#CNAE,并添加一个额外的列,指出哪个是CNAE增长最快的3个人(它将在df数据帧中添加一个数据帧)。要创建“top3dfs”我正在使用此groupby:

a=sql2.groupby('#CNAE',group_keys=False).apply(pd.DataFrame.nlargest,n=3,columns='growth')

(这个解决方案来自this question。)

它应该如下所示:

    person_code  #CNAE   growth   size              top3growth ...
0 .         231     32     0.54     32       [df_top3_type_32]
1 .         233     43     0.12    333       [df_top3_type_43]
2 .         432     32     0.44     21       [df_top3_type_32]                     
3 .         431     56     0.32     23       [df_top3_type_56]
4 .         654     89     0.12     89       [df_top3_type_89]
5 .         764     32     0.20    211       [df_top3_type_32]
6 .         434     32     0.82     90       [df_top3_type_32]
...

df_top3_type_32应如下所示(例如):

     person_code  #CNAE  growth  size
6 .          434    32    0.82    90
0 .          231    32    0.54    32
2 .          432    32    0.44    21

我试图通过使用以下方法解决我的问题:

df['top3growth']=np.nan
for i in df.index:
    df['top3growth'].loc[i]=a[a['#CNAE'] == df['#CNAE'].loc[i]]

但是我得到了:

ValueError: Incompatible indexer with DataFrame

有谁知道发生了什么?有没有更有效的方法(不使用for循环)?

python pandas pandas-groupby
1个回答
0
投票

有一种方法,将a转换为dict,然后将其映射回来

#a=df.groupby('#CNAE',group_keys=False).apply(pd.DataFrame.nlargest,n=3,columns='growth')
df['top3growth']=df['#CNAE'].map(a.groupby('#CNAE').apply(lambda x : x.to_dict()))
df
Out[195]: 
   person_code  #CNAE  growth  size  \
0          231     32    0.54    32   
1          233     43    0.12   333   
2          432     32    0.44    21   
3          431     56    0.32    23   
4          654     89    0.12    89   
5          764     32    0.20   211   
6          434     32    0.82    90   
                                          top3growth  
0  {'person_code': {0: 231, 2: 432, 6: 434}, 'gro...  
1  {'person_code': {1: 233}, 'growth': {1: 0.12},...  
2  {'person_code': {0: 231, 2: 432, 6: 434}, 'gro...  
3  {'person_code': {3: 431}, 'growth': {3: 0.32},...  
4  {'person_code': {4: 654}, 'growth': {4: 0.12},...  
5  {'person_code': {0: 231, 2: 432, 6: 434}, 'gro...  
6  {'person_code': {0: 231, 2: 432, 6: 434}, 'gro...  

创建新列后,如果要将单个单元格转换回数据帧

pd.DataFrame(df.top3growth[0])
Out[197]: 
   #CNAE  growth  person_code  size
0     32    0.54          231    32
2     32    0.44          432    21
6     32    0.82          434    90
© www.soinside.com 2019 - 2024. All rights reserved.