【问题标题】:How can I delete rows/items of pandas series with indices' labels not in a list?如何删除索引标签不在列表中的熊猫系列的行/项目?
【发布时间】:2017-01-05 09:35:38
【问题描述】:

我有一个标签列表。

我还有一个包含多个行/项目的 pandas 系列,其中一些在该列表中具有索引标签,而另一些则在该列表中没有索引标签。

我想删除该系列中标签不在该列表中的行/项目。

我能想出的唯一方法是迭代系列,检查索引标签是否在该列表中,如果没有则删除它。

还有其他更简单的方法吗?如果没有,有人可以提供这样的代码吗,因为我也无法让它工作(不知道如何迭代一个系列以及如何将其索引标签与列表中的标签进行比较)。

非常感谢您的帮助。

【问题讨论】:

  • 您是否认为像df[labels] 这样按列表选择列?或者像df.loc[labels]这样的索引值?
  • 不会df = df.drop(list_with_labels_missing) 工作?
  • 请使用相关的原始数据、您的代码、尝试和所需的输出来编辑您的问题

标签: python python-2.7 python-3.x pandas series


【解决方案1】:

您可以将Index.intersectionloc 一起使用:

s = pd.Series([1,2,5,6], index=list('abcd'))
print (s)
a    1
b    2
c    5
d    6
dtype: int64

L = list('cdef')
print (s.loc[s.index.intersection(L)])
c    5
d    6
dtype: int64

isin 的另一个可能解决方案:

print (s.loc[s.index.isin(L)])
c    5
d    6
dtype: int64

【讨论】:

    猜你喜欢
    • 2015-05-19
    • 1970-01-01
    • 2021-10-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-12-18
    • 1970-01-01
    相关资源
    最近更新 更多