我有一个1列的数据
df = pd.read_csv(txt_file, header=None)我试图在列中搜索字符串,然后返回行。
key_word_df = df[df[0].str.contains("KeyWord")]我不知道每次找到关键字时,你怎么能把它下面的行隔离起来,并分配给一个新的df。
发布于 2018-03-21 13:53:02
你可以使用移位函数。下面是一个例子
import pandas as pd
df = pd.DataFrame({'word': ['hello', 'ice', 'kitten', 'hello', 'foo', 'bar', 'hello'],
'val': [1,2,3,4,5,6,7]})
val word
0 1 hello
1 2 ice
2 3 kitten
3 4 hello
4 5 foo
5 6 bar
6 7 hello
keyword = 'hello'
df[(df['word']==keyword).shift(1).fillna(False)]
val word
1 2 ice
4 5 foo发布于 2018-03-21 13:54:52
您可以在索引器上使用.shift方法。我已经将它分成多行,以演示发生了什么,但您可以在一个一行中进行操作,以便在实践中简洁。
import pandas as pd
# 1. Dummy DataFrame with strings
In [1]: df = pd.DataFrame(["one", "two", "one", "two", "three"], columns=["text",])
# 2. Create the indexer, use `shift` to move the values down one and `fillna` to remove NaN values
In [2]: idx = df["text"].str.contains("one").shift(1).fillna(False)
In [3]: idx
Out [3]:
0 False
1 True
2 False
3 True
4 False
Name: text, dtype: bool
# 3. Use the indexer to show the next row from the matched values:
In: [4] df[idx]
Out: [4]
text
1 two
3 two发布于 2018-03-21 13:53:21
这里有一条路。
获取与条件匹配的行的索引。然后使用.loc获得匹配的索引+ 1。
请考虑以下示例:
df = pd.DataFrame({0: ['KeyWord', 'foo', 'bar', 'KeyWord', 'blah']})
print(df)
# 0
#0 KeyWord
#1 foo
#2 bar
#3 KeyWord
#4 blah应用掩码,获取索引+1的行:
key_word_df = df.loc[df[df[0].str.contains("KeyWord")].index + 1, :]
print(key_word_df)
# 0
#1 foo
#4 blahhttps://stackoverflow.com/questions/49407911
复制相似问题