【问题标题】:how to replace certain elements in the pandas dataframe index如何替换熊猫数据框索引中的某些元素
【发布时间】:2017-06-08 15:42:30
【问题描述】:

我有一本字典,想使用 .replace 仅用值替换字典键中的索引。

dicts = {"certain index element1": "changed element1",
             "certain index element2": "changed element2",
             "certain index element3": "changed element3",
             } 

这不起作用:

df.replace(dicts,regex=False,inplace=True)

df 很大,所以我无法从头开始重新分配所有索引。我只需要更改某些元素,其他一切都保持不变。

如果我想替换 df 中的某些元素(不是索引),它会起作用,但对于索引它不会。

【问题讨论】:

    标签: python pandas dictionary indexing replace


    【解决方案1】:

    使用rename(index=dicts)


    示例

    df = pd.DataFrame(
        np.random.choice(list('abcd'), (10, 10)),
        list('ABCDEFGHIJ')
    )
    dc = {'A': '_A_', 'B': '_B_'}
    
    df.rename(index=dc, inplace=True)
    
    print(df)
    
         0  1  2  3  4  5  6  7  8  9
    _A_  a  a  a  a  b  a  d  c  c  b
    _B_  b  c  c  a  a  a  b  b  a  b
    C    b  b  d  b  d  c  c  a  a  b
    D    d  d  d  d  c  b  b  a  a  d
    E    d  c  c  c  a  d  a  d  d  a
    F    d  c  d  c  d  d  d  d  b  d
    G    b  c  d  c  c  b  c  a  a  b
    H    c  c  c  b  b  a  a  b  c  a
    I    c  a  a  b  a  d  c  c  a  a
    J    a  a  a  c  a  b  d  c  c  c
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-07-23
      • 2018-10-23
      • 2018-07-02
      • 2013-12-28
      • 1970-01-01
      • 2022-01-02
      • 2019-01-08
      • 2019-03-07
      相关资源
      最近更新 更多