【问题标题】:Mapping specific index of dataframe with dictionary用字典映射数据帧的特定索引
【发布时间】:2021-10-21 11:39:10
【问题描述】:

我有数据框和字典:

d = {'col1': [11, 12, 13], 'col2': [14, 15, 16]}
dict_ = {'col1': '8', 'col2': '9'}

我的数据框有 3 个索引。这些是 0、1 和 2。我想映射最后一个索引值。 简单地说,我的愿望输出是:

   col1  col2
0    11    14
1    12    15
2     8     9

我该怎么做?

【问题讨论】:

    标签: pandas dictionary mapping


    【解决方案1】:

    如果我理解您的权利,您想用 dict_ 值更新最后一行:

    d = {"col1": [11, 12, 13], "col2": [14, 15, 16]}
    dict_ = {"col1": "8", "col2": "9"}
    
    df = pd.DataFrame(d)
    
    df.update(pd.DataFrame(dict_, index=df.index[-1:]))
    print(df)
    

    打印:

      col1 col2
    0   11   14
    1   12   15
    2    8    9
    

    【讨论】:

    • 您的解决方案是对的,谢谢。那么如何在具有许多索引的数据集中映射不是最后一个而是特定的索引呢?
    • @JuniorESE 您可以指定要更改的dfindex=。在这个例子中,我指定了最后一个索引[-1:]
    【解决方案2】:

    你可以这样做:

    df = pd.DataFrame(d)
    df.iloc[-1, :] = dict_
    

    输出:

      col1  col2
    0   11    14
    1   12    15
    2    8     9
    

    如果字典中的某些列确实存在于数据框中,它将返回 NaN。如果以不同的顺序将列放入字典中,它也将起作用。

    【讨论】:

      猜你喜欢
      • 2021-09-28
      • 2021-01-24
      • 1970-01-01
      • 2020-08-22
      • 1970-01-01
      • 2019-11-10
      • 2022-01-24
      • 2017-05-17
      • 2012-04-16
      相关资源
      最近更新 更多