【问题标题】:Subset a pandas dataframe that has an index that contains duplicates对具有包含重复项的索引的 pandas 数据框进行子集
【发布时间】:2018-08-23 08:27:25
【问题描述】:

对于数据框:

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的情况下做到这一点?

【问题讨论】:

  • 我已经回答了,但这实际上取决于您的熊猫版本..您使用的是什么版本?
  • pd.__version__ '0.23.3'
  • @adpatter 那么我相信我的回答成立..

标签: python pandas


【解决方案1】:

问题是你有重复的值NaNs 作为索引。您应该在重新索引时不考虑这些,因为它们是重复的,并且在新索引中使用哪个值存在歧义。

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,你会失败。这has actually been asked before 几次

【讨论】:

    猜你喜欢
    • 2022-10-13
    • 2019-02-16
    • 1970-01-01
    • 1970-01-01
    • 2020-07-22
    • 1970-01-01
    • 2019-12-11
    • 1970-01-01
    • 2018-03-12
    相关资源
    最近更新 更多