所以我已經閱讀了一些關于此的有用帖子,但我仍然無法弄清楚我做錯了什么。我有一本字典,我想用它來更新由一堆不同名稱組成的資料框的索引。
如果資料框的索引和字典中存在名稱,則我將其替換為新名稱。如果它不存在,那么我不會用 nan 替換,而是保留當前名稱。
這是我迄今為止嘗試過的:
第一次嘗試:
df.index = df.index.map(dictt).fillna(df.index)
錯誤:
'value' must be scalar, passed: Index
第二次嘗試
df.index = df.index.replace(dictt)
錯誤:
'Index object has no attribute 'replace'
第三次嘗試
x = dictt.keys()
for name in df.index:
if name in x:
df.index[name].map(dictt)
錯誤:
only integers, slices (`:`), ellipsis (`...`), numpy.newaxis (`None`) and integer or boolean arrays are valid indices
uj5u.com熱心網友回復:
你把它轉換成一個系列:
df.index = df.index.map(dictt).to_series(index=df.index).fillna(df.index.to_series())
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/312946.html
上一篇:C#字典與二維陣列
