用字典映射数据框的特定索引

Mapping specific index of dataframe with dictionary

我有数据框和字典:

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

我该怎么做?

如果我理解你的权利,你想用 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

你可以这样做:

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

输出:

  col1  col2
0   11    14
1   12    15
2    8     9

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