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,如果T1为: T1 = pd.DataFrame(data = {'val':['B','D','E','A','D','B','A','E','A','D','B']}) p是这样的: P = pd.DataFrame(data = {'val': ['E','A','D','B']}) 如何得到T1中p的位置 在最小值和最大值方面,我希望看到这个返回 min max 3 6 8 11 如果这些数据帧表示为SQL表,我可以使用转换为以下格式的SQL方法: DECLARE @Ite

如果T1为:

T1 = pd.DataFrame(data = {'val':['B','D','E','A','D','B','A','E','A','D','B']})
p是这样的:

P = pd.DataFrame(data = {'val': ['E','A','D','B']})
如何得到T1中p的位置

在最小值和最大值方面,我希望看到这个返回

min max
3   6
8   11
如果这些数据帧表示为SQL表,我可以使用转换为以下格式的SQL方法:

DECLARE @Items INT = (SELECT COUNT(*) FROM @P);

SELECT MIN(t.KeyCol) AS MinKey,
MAX(t.KeyCol) AS MaxKey
FROM dbo.T1 AS t
INNER JOIN @P AS p ON p.Val = t.Val
GROUP BY t.KeyCol - p.KeyCol
HAVING COUNT(*) = @Items;

此SQL解决方案来自Pesomannen对

的回复。好吧,您始终可以这样做:

t1 = ''.join(T1.val)
p = ''.join(P.val)
start, res = 0, []
while True:
    try:
        res.append(t1.index(p, start))
        start = res[-1] + 1
    except:
        break

获取起始索引,然后通过匹配计算出结束索引,并使用iloc访问数据帧。您应该使用基于0的索引,而不是基于1的索引,就像您在示例中所做的那样。

当然,这不使用p,但可以满足您的目的

groups = T1.groupby(T1.val).groups
pd.DataFrame({'min': [min(x) for x in groups.values()],
              'max': [max(x) for x in groups.values()]}, index=groups.keys())
屈服

   max  min
E    7    2
B   10    0
D    9    1
A    8    3

[4 rows x 2 columns]

我想我是通过采用与SQL解决方案相同的方法来解决这个问题的——一种关系划分类型,即匹配值,按关键列中的差异分组,然后选择计数等于子序列大小的组:

import pandas as pd

T1 = pd.DataFrame(data = {'val':['B','D','E','A','D','B','A','E','A','D','B']})

# use the index to create a new column that's going to be the key (zero based)
T1 = T1.reset_index()

# do the same for the subsequence that we want to find within T1
P = pd.DataFrame(data = {'val': ['E','A','D','B']})
P = P.reset_index()

# join on the val column
J = T1.merge(P,on=['val'],how='inner')

# group by difference in key columns calculating the min, max and count of the T1 key
FullResult = J.groupby(J['index_x'] - J['index_y'])['index_x'].agg({min,max,'count'})

# Final result is where the count is the size of the subsequence - in this case 4
FullResult[FullResult['count'] == 4]

真的很喜欢使用熊猫

你能澄清最小/最大结果吗?你是如何到达那里的?例如,在T1中EADB的第一个精确匹配的示例数据,位置3是E所在的位置,位置6是B所在的位置。对于下一个精确匹配,位置8是找到E的地方,位置11是找到B的地方。T1.reset_index.groupby'val.index.agg{min,max}我想他想要的结果是J.groupby'val'['index_x'].agg{min,max}