对于数据框: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
提交
取消