Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/310.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 在其他系列的两个索引之间创建一个新的熊猫系列_Python_Pandas - Fatal编程技术网

Python 在其他系列的两个索引之间创建一个新的熊猫系列

Python 在其他系列的两个索引之间创建一个新的熊猫系列,python,pandas,Python,Pandas,假设我有以下系列: x = pd.Series([1,1,0,0,1,1,0,0,1,1]) print(x) 0 1 1 1 2 0 3 0 4 1 5 1 6 0 7 0 8 1 9 1 我想用1和0过滤掉第一行和最后一行(即从第一行到最后一行保留一个序列)。要查找第一个和最后一个零的索引,请执行以下操作: zeros = x[x.eq(0)] from = zeros.first_valid_index() to =

假设我有以下系列:

x = pd.Series([1,1,0,0,1,1,0,0,1,1])
print(x)

0    1
1    1
2    0
3    0
4    1
5    1
6    0
7    0
8    1
9    1
我想用1和0过滤掉第一行和最后一行(即从第一行到最后一行保留一个序列)。要查找第一个和最后一个零的索引,请执行以下操作:

zeros = x[x.eq(0)]  
from = zeros.first_valid_index()  
to = zeros.last_valid_index()
现在,我想制作一个新的系列,其中包含从到之间的数据,即:

2    0
3    0
4    1
5    1
6    0
7    0
有人知道如何执行最后一步吗?或者以更快的方式执行total方法?

与change
from
to
f
一起使用,因为
from
是内置的,如果数据中至少存在一个
0
值,则解决方案有效:

zeros = x[x.eq(0)]  
f = zeros.first_valid_index()  
to = zeros.last_valid_index()

y = x.loc[f:to]
print (y)
2    0
3    0
4    1
5    1
6    0
7    0
dtype: int64
如果没有
0
值,则通用解决方案也有效:

m = x.eq(0)
y = x[(m.cumsum() * m[::-1].cumsum()).ne(0)]
print (y)
2    0
3    0
4    1
5    1
6    0
7    0
dtype: int64


from
是一个关键字,不能用作变量,请使用
loc

zeros = x[x.eq(0)]  
from_ = zeros.first_valid_index()  
to = zeros.last_valid_index()
print(x.loc[from_:to])
输出:

2    0
3    0
4    1
5    1
6    0
7    0
dtype: int64
2    0
3    0
4    1
5    1
6    0
7    0
dtype: int64