猿问

对具有包含重复项的索引的 Pandas 数据帧进行子集

对于数据框:


df = pd.DataFrame({

    'key': [1,2,3,4,5, np.nan, np.nan],

    'value': ['one','two','three', 'four', 'five', 'six', 'seven']

}).set_index('key')

看起来像这样:


        value

key     

1.0     one

2.0     two

3.0     three

4.0     four

5.0     five

NaN     six

NaN     seven

我想将其子集为:


    value

key     

1   one

1   one

6   NaN

这会产生警告:


df.loc[[1,1,6],]


Passing list-likes to .loc or [] with any missing label will raise

KeyError in the future, you can use .reindex() as an alternative.

这会产生一个错误:


df.reindex([1, 1, 6])


ValueError: cannot reindex from a duplicate axis

如何在引用缺失索引时不使用Apply的情况下执行此操作?


大话西游666
浏览 152回答 1
1回答

江户川乱折腾

题是你有重复的值NaN作为索引。您应该在重新索引时不考虑这些,因为它们是重复的,并且在新索引中使用哪个值存在歧义。df.loc[df.index.dropna()].reindex([1, 1, 6])    valuekey 1   one1   one6   NaN对于通用解决方案,请使用 duplicateddf.loc[~df.index.duplicated(keep=False)].reindex([1, 1, 6])如果您想保留重复的索引并使用reindex,您将失败。这实际上已经被问过几次
随时随地看视频慕课网APP

相关分类

Python
我要回答