對于數據框:df = pd.DataFrame({ 'key': [1,2,3,4,5, np.nan, np.nan], 'value': ['one','two','three', 'four', 'five', 'six', 'seven']}).set_index('key')看起來像這樣: valuekey 1.0 one2.0 two3.0 three4.0 four5.0 fiveNaN sixNaN seven我想將其子集為: valuekey 1 one1 one6 NaN這會產生警告:df.loc[[1,1,6],]Passing list-likes to .loc or [] with any missing label will raiseKeyError in the future, you can use .reindex() as an alternative.這會產生一個錯誤:df.reindex([1, 1, 6])ValueError: cannot reindex from a duplicate axis如何在引用缺失索引時不使用Apply的情況下執行此操作?
1 回答

江戶川亂折騰
TA貢獻1851條經驗 獲得超5個贊
題是你有重復的值NaN作為索引。您應該在重新索引時不考慮這些,因為它們是重復的,并且在新索引中使用哪個值存在歧義。
df.loc[df.index.dropna()].reindex([1, 1, 6])
value
key
1 one
1 one
6 NaN
對于通用解決方案,請使用 duplicated
df.loc[~df.index.duplicated(keep=False)].reindex([1, 1, 6])
如果您想保留重復的索引并使用reindex,您將失敗。這實際上已經被問過幾次
添加回答
舉報
0/150
提交
取消