【问题标题】:Pandas Column not found after doing an aggregation function执行聚合函数后找不到 Pandas Column
【发布时间】:2023-02-02 01:14:39
【问题描述】:

我有一个聚合函数,它根据 ID 对特定列中的行进行总计。在能够正确聚合我的行后,我想只选择相关的列,但我一直收到一条错误消息,说找不到我的 ID 列。

完整代码:

import pandas as pd
  
# initialize list of lists
data = [['A29', 112, 10, 0.3], ['A29',112, 15, 0.1], ['A29', 112, 14, 0.22], ['A29', 88, 33, 0.09], ['A29', 88, 29, 0.1], ['A29', 88, 6, 0.2]]
  
# Create the pandas DataFrame
df = pd.DataFrame(data, columns=['Id', 'Cores', 'Provisioning', 'Utilization'])

df['total'] = df['Provisioning'] * df['Utilization']

df=df[['Id', 'Cores','total']]
aggregation_functions = {'Cores': 'first', 'total': 'sum'}
df_new = df.groupby(df['Id']).aggregate(aggregation_functions)

df_new['total1']=df_new['total']/3
print(df_new) #the dataframe contains the Id columns
print(df_new.columns) #doesn't print Id column

df_new=df_new[['Id', 'total1']] #Error: Id column not found

我不确定这里发生了什么。在上面的一行中,我打印了数据框并且出现了 Id 列。但是,当我尝试选择它时,它会返回一条错误消息说找不到它?

【问题讨论】:

    标签: python pandas dataframe


    【解决方案1】:

    您应该在对.groupby()的调用中使用as_index=FalseId 列是索引的一部分,这会阻止您以所需的方式选择它:

    df_new = df.groupby(df['Id'], as_index=False).aggregate(aggregation_functions)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-11-27
      • 1970-01-01
      • 2019-11-05
      • 2021-08-24
      • 2021-12-25
      • 1970-01-01
      相关资源
      最近更新 更多