简体   繁体   English

Pandas:从系列中删除前导和尾随零值

[英]Pandas: remove leading and trailing zero values from series

I would like to remove leading and trailing zeros from a pandas series, ie input like 我想从熊猫系列中删除前导和尾随零,即输入如

my_series = pandas.Series([0,0,1,2,0,3,4,0,0])

should yield 应该屈服

pandas.Series([1,2,0,3,4])

as output. 作为输出。

I could do this recursively by removing the first (and last) zero and then calling the method again. 我可以通过删除第一个(和最后一个)零然后再次调用该方法来递归地执行此操作。 Is there a more pythonic way of doing this? 有更多的pythonic方式吗?

You can use numpys trim_zeros function. 你可以使用numpys trim_zeros函数。

import pandas
import numpy
my_series = pandas.Series([0,0,1,2,0,3,4,0,0])
numpy.trim_zeros(my_series)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM