【问题标题】:append missing names to end of a groupby pandas将缺少的名称附加到 groupby pandas 的末尾
【发布时间】:2020-09-06 14:43:59
【问题描述】:

我正在处理一个报告自动化任务,我使用 groupby 函数生成了一个表格

function_d= {"AvgLoadCur": 'mean'}
newdf=df.groupby(['sitename']).agg(function_d)
sitename                       AvgLoadCur
Biocon-SEZD-66/11KV SS 11          23.0
Biocon-SEZD-GT 1 120V DC           24.2
Biocon-SEZD-GT 2 120V DC           23.9
Biocon-SEZD-PLC 24V                21.4

df 仅包含 4 个站点名称,因此 groupby 表也仅包含这四个我如何附加存储在另一个数据框 site['sitename'] 中的丢失的两个站点名称

sitename
Biocon-SEZD-GT 1 120V DC
Biocon-SEZD-GT 2 120V DC
Biocon-SEZD-SCADA UPS
Biocon-SEZD-66/11KV SS 11
Biocon-SEZD-PLC 24V DC
BIOCON SEZ-HT PANEL 220 V

最终的 Dataframe 应该是这样的

sitename                       AvgLoadCur
Biocon-SEZD-66/11KV SS 11          23.0
Biocon-SEZD-GT 1 120V DC           24.2
Biocon-SEZD-GT 2 120V DC           23.9
Biocon-SEZD-PLC 24V                21.4
  Biocon-SEZD-HT PANEL 220 V          --
  Biocon-SEZD-SCADA UPS               --

简而言之,如何从另一个数据框中附加 groupby 表中不存在的元素

分组表:

Fruit  Price
apple    34

一个df表

Fruit
--------
apple 
orange

最终分组表

Fruit  Price
apple    34
orange   --

【问题讨论】:

    标签: python pandas numpy dataframe group-by


    【解决方案1】:

    您可以先合并您的数据框,然后再进行分组。

    df = pd.DataFrame({'Fruit': {0: 'apple'}, 'Price': {0: 34}})
    df2 = pd.DataFrame({'Fruit': {0: 'apple', 1: 'orange'}})
    
    (
        pd.merge(df,df2,on='Fruit',how='right')
        .groupby('Fruit')
        .agg(avg=('Price', 'mean'))
        .reset_index()
    )
    
        Fruit   avg
    0   apple   34.0
    1   orange  NaN
    

    【讨论】:

    • @Harish Reddy 这应该是公认的答案,尽可能避免在熊猫中循环
    【解决方案2】:

    我希望这能回答你的问题:

    df = pd.DataFrame([['apple',1],['orange',2]],columns=['Fruit','Price'])
    df2 = pd.DataFrame(['guava','apple','orange'],columns=['Fruit'])
    for value in df2['Fruit'].values:
        if value not in df['Fruit'].values:
            df = df.append({'Fruit':value,'Price':'--'},ignore_index=True)
    df
    

    输出

    
        Fruit   Price
    0   apple   1
    1   orange  2
    2   guava   --
    

    【讨论】:

    • 尽量避免循环,您可以将mergeconcat 与许多矢量化函数一起使用。
    猜你喜欢
    • 2015-04-11
    • 2012-11-20
    • 1970-01-01
    • 2013-11-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-05-06
    • 2017-06-15
    相关资源
    最近更新 更多