问题:我必须在系列集中循环以找出系列值是否包含子集字符串“Hi”?
说明:这里有两个数据帧 Dataframe1 和 Dataframe2,我试图查找 Dataframe2 的“源代码”是否包含 Dataframe1 的字符串并将结果设置在 Dataframe3 中。
import pandas as pd
import numpy as np
import openpyxl
data = {'Fields' : ['Hi', 'How', 'Are', 'You']}
Dataframe1 = pd.DataFrame(data)
data2 = {'SourceCode' : ['LMNOHiPQR', 'LMNOHowPQR']}
Dataframe2 = pd.DataFrame(data2)
data3 = {'dummy' : []}
Dataframe3 = pd.DataFrame(data3)
for i in range(0,len(Dataframe1)):
current_string=Dataframe1['Fields'][i]
for j in range(0,len(Dataframe2)):
if Dataframe2['SourceCode'].iloc[j].contains(current_field):
Dataframe3['dummy'].iloc[j] =Dataframe2['SourceCode'].iloc[j]
期望:我期望包含 Dataframe1 中的字符串的“SourceCode”值在 Dataframe3 中设置。但我收到以下错误。
RESULT:
if Dataframe2['SourceCode'].iloc[j].contains(current_field):
AttributeError: 'str' object has no attribute 'contains'
伙计们,作为上一个问题的补充,我现在想在 Dataframe3 中添加一个带有相应字符串(即 current_field)的单独列。因此我会知道观察对应于哪个字符串。请帮我解决这个问题。
最佳答案
IIUC 你应该使用 in
运算符来测试字符串中是否存在子字符串,因此循环应该类似于:
for i in range(0,len(Dataframe1)):
current_string=Dataframe1['Fields'][i]
for j in range(0,len(Dataframe2)):
if current_string in Dataframe2['SourceCode'].iloc[j]:
Dataframe3.loc[j, 'dummy'] = Dataframe2['SourceCode'].iloc[j]
但是,不建议使用 pandas.DataFrames
进行循环。因此,替代解决方案可能是使用 Series.str.contains
方法和boolean indexing
:
Dataframe3 = Dataframe2[Dataframe2.SourceCode.str.contains('|'.join(Dataframe1.Fields))]
[输出]
SourceCode
0 try{string s = "Hi"}catch { }return null;
1 try{string s = "How"}catch { }return null;
如果您需要匹配包含单词边界,请首先创建正则表达式模式,例如:
pat = r'\b' + r'\b|\b'.join(Dataframe1.Fields) + r'\b'
Dataframe3 = Dataframe2[Dataframe2.SourceCode.str.contains(pat)]
关于python - 我们可以在 pandas 的 iloc 中使用 contains 属性吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56073079/