【问题标题】:Pandas replacing values in a column by values in another column熊猫用另一列中的值替换列中的值
【发布时间】:2021-08-31 12:15:02
【问题描述】:

假设我有以下数据框 X(ppid 是唯一的):

    ppid  col2 ...
1   'id1'  '1'
2   'id2'  '2'
3   'id3'  '3'
...

我有另一个用作映射的数据框。 ppid 与上面相同并且是唯一的,但是它可能不包含所有 X 的 ppid:

    ppid  val
1   'id1' '5'
2   'id2' '6'

我想使用映射数据框根据 ppid 相等的位置切换数据框 X 中的 col2(实际上,它们是多个唯一的列),以获得:

    ppid  col2 ...
1   'id1'  '5'
2   'id2'  '6'
3   'id3'  '3' # didn't change, as there's no match
...

【问题讨论】:

  • ppid上的第二个DataFrame与how='left'合并,并使用fillna填补空白

标签: python pandas dataframe


【解决方案1】:

查看 Jeremy Z 对此帖子的回答,以进一步了解解决方案 https://stackoverflow.com/a/55631906/16235276

df1 = df1.set_index('ppid')
df2 = df2.set_index('ppid')
df1.update(df2)
df1.reset_index(inplace=True)

【讨论】:

    【解决方案2】:

    尝试将mapset_index 一起使用:

    df_x = pd.DataFrame({'ppid':['id1','id2','id3'], 'col2':[*'123']})
    
    df_a = pd.DataFrame({'ppid':['id1','id2'], 'val':[*'56']})
    
    df_x['col2'] = df_x['ppid'].map(df_a.set_index('ppid')['val']).fillna(df_x['col2'])
    

    输出:

      ppid col2
    0  id1    5
    1  id2    6
    2  id3    3
    

    【讨论】:

    • AttributeError: 'DataFrame' 对象没有属性 'map'
    • df_x['ppid'] 不是 DataFrame,它是一个系列。此代码适用于您的示例。
    • df_x 实际上有更多的列,为简洁起见省略了...这是一个小修复吗?
    • 这没关系。我们只是在 df_x 中创建一个名为 'Col2' 的新列,df_x 中的所有列都保持不变并且不受影响。
    【解决方案3】:

    输入数据:

    >>> dfX
        ppid col1 col2 col3
    0  'id1'  'X'  '5'  'A'
    1  'id2'  'Y'  '6'  'B'
    2  'id3'  'Z'  '3'  'C'
    
    >>> dfM
        ppid  val
    0  'id1'  '5'
    1  'id2'  '6'
    

    dfX 是您的第一个数据框,dfM 是您的映射数据框:

    >>> dfM.rename(columns={'val': 'col2'}).combine_first(dfX).loc[:, df.columns]
    
        ppid col1 col2 col3
    0  'id1'  'X'  '5'  'A'
    1  'id2'  'Y'  '6'  'B'
    2  'id3'  'Z'  '3'  'C'
    

    【讨论】:

    • 我更新了我的答案。我认为您的列排列有问题,是吗?
    【解决方案4】:

    首先合并您的数据框,然后使用pd.Series.combine_first

    df1 = pd.merge(df1, df2, how='left', on='ppid')
    df1['col2'] = df1.val.combine_first(df1.col2)
    del df1['val']
    

    【讨论】:

      【解决方案5】:
      df1 = pd.DataFrame({'ppid': ['id1', 'id2', 'id3'], 'col2': ['1', '2', '3']})
      df2 = pd.DataFrame({'ppid': ['id1', 'id2'], 'col2': ['5', '6']})
      
      merged = df1.merge(df2, how='left', on='ppid')
      merged['col2_y'].fillna(merged['col2_x'], inplace=True)
      
      merged
      
        ppid col2_x col2_y
      0  id1      1      5
      1  id2      2      6
      2  id3      3      3
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2018-11-04
        • 1970-01-01
        • 2020-10-27
        • 1970-01-01
        • 2019-08-01
        • 2023-02-25
        • 2015-01-19
        相关资源
        最近更新 更多