Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/289.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,我有这样一个数据框: df1 = pd.DataFrame({'col1':range(1,10,1),'col2':range(100,1000,100)}) col1 col2 0 1 100 1 2 200 2 3 300 3 4 400 4 5 500 5 6 600 6 7 700 7 8 800 8 9 900 以下是我的时间间隔的开始和结束索引: sta_idxs = pd.Series([3,6],

我有这样一个数据框:

df1 = pd.DataFrame({'col1':range(1,10,1),'col2':range(100,1000,100)})

   col1 col2
0   1   100
1   2   200
2   3   300
3   4   400
4   5   500
5   6   600
6   7   700
7   8   800
8   9   900
以下是我的时间间隔的开始和结束索引:

sta_idxs = pd.Series([3,6], index=['col1','col2'])
end_idxs = pd.Series([5,7], index=['col1','col2'])

sta_idxs         end_idxs
col1    3        col1     5
col2    6        col2     7
dtype: int64     dtype: int64
我想对col1(4+5+6)中索引3和5之间以及col2(700+800)中索引6和7之间的数字求和。 预期结果将是:

col1 15
col2 1500
我正在寻找一个矢量化的解决方案,以避免循环通过列


非常感谢您的帮助。

对于一般情况和一些过度使用,我们可以使用
rolling
lookup

pd.Series(df1.rolling(3).sum()
             .lookup(end_idxs, end_idxs.index),
          index=end_idxs.index)
输出:

col1      15.0
col2    2100.0
dtype: float64

对于一般情况和一些过度使用,我们可以使用
rolling
lookup

pd.Series(df1.rolling(3).sum()
             .lookup(end_idxs, end_idxs.index),
          index=end_idxs.index)
输出:

col1      15.0
col2    2100.0
dtype: float64

我想ypu正在寻找这样的东西
df1.loc[end\u idx[0]-2:end\u idx[0]['col1'].sum()
df1.loc[end\u idx[1]-2:end\u idx[1]['col2'].sum()
但我不确定你想如何表达他们谢谢你的评论!问题是,我不想逐列循环,对结果序列进行切片,然后将结果附加到新序列中。(如果我能很好地理解你的建议)我正在寻找一个矢量化的解决方案。你能提供更多的例子吗?这样我就能更好地理解你在寻找什么。我想ypu正在寻找类似这样的东西。loc[end_idx[0]-2:end_idx[0]['col1'].sum()和
df1.loc[end_idx[1]-2:end_idx[1]['col2'].sum()
但我不确定您想如何代表他们谢谢您的评论!问题是,我不想逐列循环,对结果序列进行切片,然后将结果附加到新序列中。(如果我能很好地理解你的建议)我正在寻找一个矢量化的解决方案。你能提供更多的例子吗?这样我就能更好地理解你在寻找什么汉克斯,它节省了我的时间,而且非常简洁!在整个数据库中使用一个比sum()更奇特的函数进行滚动操作,这确实是一种过分的做法。也不能用于我问题的第二部分,关于可变长度间隔。不过,这还是一个有用的建议!您的回答揭示了我的示例中的一个隐式错误,即建议所有列的间隔大小相等。对于那个特殊情况,你的解决方案是正确的,但那不是我的初衷。很抱歉我已经改正了我的例子,以便更好地思考一般问题。我可以避免重复列吗?谢谢,它节省了我的时间,而且非常简洁!在整个数据库中使用一个比sum()更奇特的函数进行滚动操作,这确实是一种过分的做法。也不能用于我问题的第二部分,关于可变长度间隔。不过,这还是一个有用的建议!您的回答揭示了我的示例中的一个隐式错误,即建议所有列的间隔大小相等。对于那个特殊情况,你的解决方案是正确的,但那不是我的初衷。很抱歉我已经改正了我的例子,以便更好地思考一般问题。我可以避免迭代列吗?