在 pandas DataFrame 中查找有条件的连续值

3
我有一个pandas数据框,其中包含多行和多列,填充了类型和值。所有的值都是字符串。我想要编写一个函数来满足以下条件: 1)我搜索的类型(列1) 2)第一个值(列2) 3)第二个连续值(在列2的下一行)
我成功地编写了一个可以搜索一个类型的一个值的函数,但是如何添加第二个类型呢?我觉得可能需要使用df.shift(axis=0)命令来实现,但我不知道如何将该命令与条件搜索组合起来。
import pandas as pd

d = {'type': ['wordclass', 'wordclass', 'wordclass', 'wordclass', 'wordclass', 'wordclass',
 'english', 'english', 'english', 'english', 'english', 'english'],
 'values': ['dem', 'noun', 'cop', 'det', 'dem', 'noun', 'this', 'tree', 'is', 'a', 'good', 'tree']}
df = pd.DataFrame(data=d)
print(df)

tiername = 'wordclass'
v1 = 'dem'
v2 = 'noun'

def search_single_tier(tiername, v1):
    searchoutput = df[df['type'].str.contains(tiername) & df['values'].str.match(v1)]
    return searchoutput

x = search_single_tier(tiername, v1)
print(x)```


为了更清晰,您需要一个接收三个参数:x、y、z的函数,并返回一行数据,其中x是列1的值,y是列2的值,z是下一行中列1为x的值? - Roim
是的,那就是我想要的。 - Eline
1个回答

1

您不需要为此创建一个函数。相反,可以尝试以下方法:

In [422]: tiername = 'wordclass'                                                                                                                                                                            

## This equates `type` columns to `tiername`. 
## `.iloc[0:2]` gets the first 2 rows for the matched condition

In [423]: df[df.type.eq(tiername)].iloc[0:2]                                                                                                                                                                
Out[423]: 
        type values
0  wordclass    dem
1  wordclass   noun

Op发表评论后:

Find all consecutive rows like this:
tiername = 'wordclass'
v1 = 'dem'

In [455]: ix_list = df[df.type.eq(tiername) & df['values'].eq(v1)].index.tolist()

In [464]: pd.concat([df.iloc[ix_list[0]: ix_list[0]+2], df.iloc[ix_list[1]: ix_list[1]+2]])                                                                                                                 
Out[464]: 
        type values
0  wordclass    dem
1  wordclass   noun
4  wordclass    dem
5  wordclass   noun

是的,那样做是可以的,但我想要能够更改我正在查找的值,并且它不会给我所有连续的dem和noun值(在mwe中有两个这样的组合)。 - Eline
1
@Eline 请检查我的回答的第二部分。已更新。 - Mayank Porwal
如果我正确理解了此更新,那么我无法更改第二个值,它只是给出了紧随v1后面的值。我想要能够找出是否可以在我的数据库中自行设置一个v2来跟随v1,例如,如果“dem”也可以跟随“cop”或“det”。 - Eline
我的更新基本上是针对特定的 tiernamev1,返回下一行具有相同 tiernamev1 的值。我原以为这就是问题所在。现在,你让我感到困惑了。 - Mayank Porwal
用通俗的语言来说:我对我的数据库中哪些单词和词类的组合被发现(或未被发现)感兴趣。例如:单词“this”能跟在单词“tree”后面吗?词类“det”能在词类“noun”前面吗?我还对频率感兴趣。用Roim在原帖下的话来说:我想要一个接收三个参数x、y、z并返回所有行的函数,其中x是column1的值,y是column2的值,z是下一行的值(该行也有x在column1中)。 - Eline

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接