首页 > 解决方案 > 用 dict 替换数据框行

问题描述

我有来自数据框的以下行:

print(row) =  

a      Nan
b      NaN
c      NaN
d      NaN
e      NaN

我有一个字典:dict1 = {'a': 1, 'b': 2, 'c': 3, 'd': 4, 'e': 5}我想用它替换这一行。

我尝试了熊猫系列替换row = row.replace(dict1, regex=True) ,但它不起作用。我怎样才能做到这一点?

标签: pythonpandas

解决方案


采用:

s = pd.Series(row.index.map(dict1.get), index=row.index)
print (s)
a    1
b    2
c    3
d    4
e    5
dtype: int64

如果只想替换索引:

row.index = row.index.map(dict1.get)

推荐阅读