【问题标题】:Merge rows with same index and prioritize column values合并具有相同索引的行并优先考虑列值
【发布时间】:2021-10-15 04:23:02
【问题描述】:

我有一个数据框,其中包含一些重复的索引值,其中的列包含两个不同实验的值。如果两个索引实例中都存在值,我想优先考虑 Col_A。我正在努力使用以下算法解决此解决方案。

  1. 合并具有相同索引的行

Pandas merging rows with the same value and same index

  1. 使用 combine_first 函数创建新列。如果存在则选择 Col_A,否则选择 Col_B

示例数据

data = {'id':['id3', 'id3', 'id6'],
       'Col_A':[11,NaN,3],
       'Col_B':[NaN,5,NaN]}

## Insert SO Magic Here

##

output = {'id':['id3', 'id6'],
       'Col_Score':[11,3]}

如果有比我提出的算法“更好”的解决方案(更短),请告诉我。

【问题讨论】:

    标签: python pandas dataframe indexing data-munging


    【解决方案1】:

    如果您保证每个 id 没有重复的列,那么data(或者更确切地说是pd.DataFrame(data))可以很容易地重新格式化:

    >>> ser = data.set_index('id').stack()
    >>> ser
    id        
    id3  Col_A    11.0
         Col_B     5.0
    id6  Col_A     3.0
    dtype: float64
    

    附带说明,如果您再次将其拆开,您将获得具有唯一索引的原始数据的更密集版本:

    >>> ser.unstack()
         Col_A  Col_B
    id               
    id3   11.0    5.0
    id6    3.0    NaN
    

    我们可以用groupby而不是.unstack()来选择第一项,例如:

    >>> ser.groupby('id').first().rename('Col_score')
    id
    id3    11.0
    id6     3.0
    Name: Col_Score, dtype: float64
    

    然后您可以通过.reset_index() 获取数据帧而不是序列。

    【讨论】:

      【解决方案2】:

      这是使用melt的解决方案:

      (df.melt(id_vars=['id'], value_name='Col_Score') # Col_A will be above Col_B
         .dropna()                                     # remove NaN rows
         .groupby('variable', as_index=False)
         .first()                                      # keep first per group (i.e. Col_A when both)
         .drop('variable', axis=1)                     # cleanup
      )
      

      输出:

          id  Col_Score
      0  id3       11.0
      1  id3        5.0
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2022-01-27
        • 1970-01-01
        • 2017-01-31
        • 2021-07-28
        • 2021-07-30
        • 1970-01-01
        • 2023-03-24
        • 2017-04-14
        相关资源
        最近更新 更多