【问题标题】:Aggregating Rows Pandas聚合行 Pandas
【发布时间】:2018-07-08 09:26:37
【问题描述】:

我对@9​​87654321@ 很陌生。如果'Names' 具有相同的名称,我需要汇总它们,然后对'Rating''NumsHelpful' 求平均值(不计算NaN)。 'Review' 应该被连接起来,而 'Weight(Pounds)' 应该保持不变:

col names: ['Brand', 'Name', 'NumsHelpful', 'Rating', 'Weight(Pounds)', 'Review']

Name             'Brand'                             'Name'
1534             Zing Zang                Zing Zang Bloody Mary Mix, 32 fl oz   
1535             Zing Zang                Zing Zang Bloody Mary Mix, 32 fl oz   
1536             Zing Zang                Zing Zang Bloody Mary Mix, 32 fl oz   
1537             Zing Zang                Zing Zang Bloody Mary Mix, 32 fl oz   
1538             Zing Zang                Zing Zang Bloody Mary Mix, 32 fl oz   
1539             Zing Zang                Zing Zang Bloody Mary Mix, 32 fl oz   
1540             Zing Zang                Zing Zang Bloody Mary Mix, 32 fl oz   

        'NumsHelpful'     'Rating'       'Weight'
1534          NaN            2              4.5   
1535          NaN            2              4.5   
1536          NaN            NaN            4.5   
1537          NaN            NaN            4.5   
1538          2              NaN            4.5   
1539          3              5              4.5   
1540          5              NaN            4.5   

                        'Review'
1534                                     Yummy - Delish  
1535  The best Bloody Mary mix! - The best Bloody Ma...  
1536  Best Taste by far - I've tried several if not ...  
1537  Best bloody mary mix ever - This is also good ...  
1538  Outstanding - Has a small kick to it but very ...  
1539   OMG! So Good! - Spicy, terrific Bloody Mary mix!  
1540                      Good stuff - This is the best  

所以输出应该是这样的:

 'Brand'                'Name'                   'NumsHelpful'    'Rating' 
Zing Zang    Zing Zang Bloody Mary Mix, 32 fl oz     3.33             3

 'Weight'               'Review'
   4.5      Review1 / Review2 / ... / ReviewN

我该如何处理?谢谢。

【问题讨论】:

    标签: python pandas dataframe pandas-groupby


    【解决方案1】:

    DataFrameGroupBy.agg 与列字典和聚合函数一起使用 - 列 WeightBrandfirst 聚合 - 这意味着每个组的第一个值:

    d = {'NumsHelpful':'mean', 
         'Review':'/'.join, 
         'Weight':'first',
         'Brand':'first', 
         'Rating':'mean'}
    df = df.groupby('Name').agg(d).reset_index()
    print (df)
                                      Name  NumsHelpful  \
    0  Zing Zang Bloody Mary Mix, 32 fl oz     3.333333   
    
                                                  Review  Weight      Brand  \
    0  Yummy - Delish/The best Bloody Mary mix! - The...     4.5  Zing Zang   
    
       Rating  
    0     3.0  
    

    同样在pandas 0.23.1 pandas 版本中获取:

    FutureWarning:“名称”既是索引级别又是列标签。 默认为列,但这会在未来的版本中引发歧义错误

    解决方案是删除索引名称Name

    df.index.name = None
    

    或者:

    df = df.rename_axis(None)
    

    另一个可能的解决方案不是由first 聚合,而是将这些列添加到groupby

    d = {'NumsHelpful':'mean',  'Review':'/'.join, 'Rating':'mean'}
    df = df.groupby(['Name', 'Weight','Brand']).agg(d).reset_index()
    

    如果每组有相同的值,两种解决方案都会返回相同的输出。

    编辑:

    如果需要将字符串(对象)列转换为数字,请先尝试通过astype进行转换:

    df['Weight(Pounds)'] = df['Weight(Pounds)'].astype(float)
    

    如果失败,请使用 to_numeric 和参数 errors='coerce' 将不可解析的字符串转换为 NaNs:

    df['Weight(Pounds)'] = pd.to_numeric(df['Weight(Pounds)'], errors='coerce')
    

    【讨论】:

    • 我尝试使用您的建议,但我的错误仍然存​​在:/
    • @StefanoPozzi - 数据保密吗?
    • 否,但设法修复它:) 必须将我想要包含字符串的列转换为字符串类型。谢谢帮忙!
    【解决方案2】:

    您可以使用groupby + agg 为每列使用不同的函数进行聚合,并使用字典映射系列到函数。例如:

    d = {'Rating': 'mean',
         'NumsHelpful': 'mean',
         'Review': ' | '.join,
         'Weight(Pounds)': 'first'}
    
    res = df.groupby('Name').agg(d)
    

    【讨论】:

    • 'mean' 是 np.mean 还是字符串?因为当我尝试运行代码时,它给了我一个 'TypeError: sequence item 0: expected str instance, float found'
    • 这是输出'Brand object - Name object - NumsHelpful float64 - Rating float64 - Weight(Pounds) object - Review object' 这是否意味着重量有一些非浮动参数?
    • @StefanoPozzi - 你的熊猫版本是什么?
    • @StefanoPozzi - object 表示它显然是字符串列。
    • version = 0.22.0 / 我试过用这个 -> pd.to_numeric(df['Weight(Pounds)']) 但似乎没有做任何改变(仍然是对象)
    【解决方案3】:

    我已经看到这种情况发生,因为在创建索引时您选择将列保留在列表中,通常指向索引的列会从表中排除,因此请执行以下操作:

    # dataset_A was created with the option # drop = False
    df_dataset_new = dataset_A.copy()
    index_df = ['month', 'scop']
    
    # dataset_new will be create`enter code here`d with the option # drop = True
    df_dataset_new.set_index(index_df, drop=True, inplace=True, verify_integrity=True) 
    

    【讨论】:

      猜你喜欢
      • 2018-04-16
      • 2021-12-05
      • 1970-01-01
      • 2019-09-06
      • 1970-01-01
      • 2021-08-24
      • 2019-05-15
      • 2014-11-23
      相关资源
      最近更新 更多