python - 如何使 FOR 循环中的 IF 在 DataFrame 上工作?Python
问题描述
我正在尝试根据段应该开始的词对来选择句子的段/子句。例如,我对以“what does”或“what is”等开头的句子片段感兴趣。
为此,我在两个 DataFrame 上循环,使用如下所示的if statement
内部 a 。for loop
第一个 DataFramedf1['Sentence']
包含句子。另一个df2['First2']
包含成对的起始词。但是,该函数似乎只在第一项之后的 - 中的第一个单词对上循环for loop
,它不会返回到 for 循环。当我将列表传递给它时,我的代码似乎可以工作,但当我传递 DataFrames 时却不行。我已经尝试过Pythonic 方式中提到的将 FOR 循环和 IF 语句结合起来的解决方案。但它们不适用于我的 DataFrame。我很想知道如何解决这个问题。
数据框:
'Sentence' 'First2'
0 If this is a string what does it say? 0 what does
1 And this is a string, should it say more? 1 should it
2 This is yet another string. 2
我的代码如下所示:
import pandas as pd
a = df1['Sentence']
b = df2['First2']
#The function seems to loop over all r's but not over all b's:
def func(r):
for i in b:
if i in r:
# The following line selects the sentence segment that starts with
# the words in `First2`, up to the end of the sentence.
q = r[r.index(i):]
return q
else:
return ''
df1['Clauses'] = a.apply(func)
这是结果:
what does it say?
这是正确但不完整的。代码似乎遍历了 all r
,但没有遍历 all b
。如何得到想要的结果,如下?
what does it say?
should it say more?
解决方案
我不确定我是否做对了,但看起来你想存储来自'First2'
(比如说一个变量s
)的所有短语,并且有一个列'Clauses'
是与任何匹配后的字符串的其余部分中包含的短语s
。
可能有一种更有效的方法,但这里有一种用正则表达式执行此操作的 hacky 方法:
# build the capturing string
s = '(' + '|'.join(df.First2[df.First2 != ''].values + '.*') + ')'
# use the pandas Series.str method to extract, and assign to new column
df['Clauses'] = df.Sentence.str.extract(s, expand = False)
推荐阅读
- javascript - 使用 AJAX 从 Node.js 调用 PHP 文件?
- css - 混合模式在 Chrome 上不起作用
- r - 根据 date.time 列创建新列并填充行值
- c# - 使用 Angular 前端在 .Net Core 2.1 中无法使用 Jwt 进行身份验证
- java - 数学表达式的分词器
- sql-server - 在一个查询中查找多个最大日期
- java - 按钮数组导致应用程序崩溃
- javascript - 如何按升序对对象数组进行排序?
- java - Android Studio:无法启动活动 ComponentInfo:java.lang.illegalStateException:RecyclerVIew 没有 LayoutMAnager
- xcode - 无法输入 Xcode 助手编辑器