Python 对数据帧中一组索引之间的行进行计数
我在计算来自另一个数据帧的两个索引之间的行数时遇到问题。让我用一个例子来解释这一点: DF2的索引是参考向量,我想计算DF1中两个索引之间的行数/条目数Python 对数据帧中一组索引之间的行进行计数,python,pandas,dataframe,Python,Pandas,Dataframe,我在计算来自另一个数据帧的两个索引之间的行数时遇到问题。让我用一个例子来解释这一点: DF2的索引是参考向量,我想计算DF1中两个索引之间的行数/条目数 DF1 DF2 data data index index 3 1 2 1 9 1
DF1 DF2
data data
index index
3 1 2 1
9 1 11 1
15 0 33 1
21 0 34 1
23 0
30 1
34 0
现在我想计算df2中两个索引之间的所有行。
参考向量是DF2的索引向量:[2,11,33,34]
Between index 2 and 11 of DF2 is index: 3 and 9 of DF1 -> result 2
Between index 11 and 33 of DF2 is index: 15, 21, 23, 30 of DF1 -> result 4
Between index 33 and 34 of DF2 is index: 34 of DF1 -> result 1
因此,结果向量应该是:[2,4,1]
这真的很艰难,所以我希望你能帮助我 If将首先构建一个数据帧,给出来自
df2
的最小和最大索引:
limits = pd.DataFrame({'mn': np.roll(df2.index, 1), 'mx': df2.index}).iloc[1:]
它给出:
mn mx
1 2 11
2 11 33
3 33 34
然后很容易使用理解来获得预期列表:
result = [len(df1[(i[0]<=df1.index)&(df1.index<=i[1])]) for i in limits.values]
[2, 4, 1]