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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/34641056/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 15:17:16  来源:igfitidea点击:

Removing elements from pandas series in python

pythonrpandasseries

提问by jay2020

I have a series data type which was generated by subtracting two columns from pandas data frame.

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

I want to remove the first element from the series which would be x[-1]in R. I can get it to work in np array class but series class doesn't work.

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

采纳答案by Stefan

Using integerbased slicing should work - (see docs):

使用integer基于切片应该可以工作 - (参见文档):

s.iloc[1:]

If you prefer to droprather than slice, you could use the built-in dropmethod:

如果您更喜欢drop而不是slice,则可以使用内置drop方法:

s.drop(s.index[0])

To remove several items, you would include a listof indexpositions:

要删除几个项目,你将包括listindex位置:

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

or a slice:

slice

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

回答by johnchase

Python doesn't have a way of slicing out a position the way that R does. If you only need to remove the first or last element, the previous posted solution: s.iloc[1:]is probably the best. If you need to remove multiple elements, or an element in the middle of your series you can do so with the following:

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

In this case we removed the 0, 3 and 4 positions.

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

This is a bit messier, so like I said the previous solution may be the best for what you need, however this does have some additional functionality.

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

It's worth noting that this solution will only work if your index is numeric and consecutive starting with 0.

值得注意的是,此解决方案仅适用于您的索引为数字且从 0 开始连续的情况。