从 python 中的 pandas 系列中删除元素

Removing elements from pandas series in python

我有一个系列数据类型,它是通过从 pandas 数据框中减去两列生成的。

我想从 R 中的系列中删除第一个元素 x[-1]。我可以让它在 np 数组 class 中工作,但系列 class 没有工作。

使用基于 integer 的切片应该有效 - (see docs):

s.iloc[1:]

如果您更喜欢 drop 而不是 slice,您可以使用 built-in drop 方法:

s.drop(s.index[0])

要删除多个项目,您需要包含 listindex 个位置:

s.drop(s.index[[0, 2, 4]])

slice:

s.drop(s.index[1: 4])

Python 没有像 R 那样分割位置的方法。如果您只需要删除第一个或最后一个元素,那么之前发布的解决方案:s.iloc[1:] 可能是最好的。如果您需要删除多个元素,或系列中间的一个元素,您可以使用以下方法:

In [29]: x = pd.Series(np.random.randn(10))

In [34]: x[~x.index.isin([0, 3, 4])]
Out[34]: 1    0.884089
         2    0.921271
         5   -0.847967
         6   -0.088892
         7   -0.765241
         8   -0.084489
         9   -0.581152
         dtype: float64

在这种情况下,我们删除了 0、3 和 4 位置。

这有点混乱,所以就像我说的,以前的解决方案可能最适合您的需要,但是它确实有一些额外的功能。

值得注意的是,只有当您的索引是数字且从 0 开始连续时,此解决方案才有效。