【问题标题】:In a Pandas dataframe, how to replace all elements x with element y?在 Pandas 数据框中,如何用元素 y 替换所有元素 x?
【发布时间】:2018-02-23 09:42:57
【问题描述】:

我有一个大数据框df,14 列 * 800 行。独立地,我有两列的文件(让我们说这些条目):

car          one
bus          two
bike         three
...          

我想搜索数据框df 并将左列中出现的所有值替换为右列中同一行中的相应元素 - 意味着,无论我在哪里找到“汽车”作为我替换的数据框中的条目它用“one”,无论我在哪里找到“bus”,我都会用“two”代替它,等等。我找到了 pandas 的函数 .replace 和 .isin,但我缺乏将它们结合起来的技能。

谁能告诉我如何在数据框中进行替换?


建议的解决方案:

将列(汽车、公共汽车、自行车……)和(一、二、三……)读入 numpy-array-lists,例如(car, bus, bike,...) 到 list_old 和 (一, 二, 三,...) 到 list_new。例如,这可以通过 pandas pd.read_fwf 实现。然后可以使用 pandas 的 .replace 函数的便捷功能:

df.replace(to_replace=list_old, value=list_new, inplace=True)

这就是诀窍!请注意,它还负责按索引进行匹配(list_old[n] 替换为 list_new[n])

【问题讨论】:

    标签: python pandas search dataframe replace


    【解决方案1】:

    我认为你可以通过Series 使用set_index 创建DataFrame.replace

    df = df.replace(df.set_index('col1')['col2'])
    

    dict

    df = df.replace(df.set_index('col1')['col2'].to_dict())
    

    示例:

    df = pd.DataFrame({'col1':['car','bus','bike'],
                       'col2':['one','two','three'],
                       'col3':['car','bike','bike']})
    print (df)
       col1   col2  col3
    0   car    one   car
    1   bus    two  bike
    2  bike  three  bike
    
    df = df.replace(df.set_index('col1')['col2'])
    print (df)
        col1   col2   col3
    0    one    one    one
    1    two    two  three
    2  three  three  three
    

    【讨论】:

      【解决方案2】:

      假设您将文件加载到数据框df1。先用它来生成映射:

      mapping = dict(df1[['col1', 'col2'].values)
      

      或者,

      mapping = df1.set_index('col1')['col2']
      

      现在在您的实际数据帧上调用df.replace,例如df2

      df2.replace(mapping)
      

      或者,您可以使用df.map - 不匹配的将转换为NaN

      df2.map(mapping)
      

      【讨论】:

      • mapping = df1.set_index('col1')['col2']
      猜你喜欢
      • 1970-01-01
      • 2020-08-08
      • 1970-01-01
      • 2012-08-26
      • 2012-01-31
      • 1970-01-01
      • 2023-03-19
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多