2017-07-06 21 views
0

嗨,所以我想要实现的是在我的csv文件(转换为数据帧)包含单词“出站”,并隔离该列,和它旁边的两列。到目前为止,我尝试了以下代码片段无济于事。使用正则表达式/搜索找到一个字符串并隔离列

mask = np.column_stack([NB_2c17_newburden[col].str.contains(r"outbound", na=False) for col in NB_2c17_newburden]) 

以及使用搜索

for line in NB_2c17_newburden: 
     if re.search('outbound', line): 
     print (line) 

我只是用打印线,看它是否会工作。任何帮助,将不胜感激。

在该R已经实现了与下面的代码:

i <- grep('outbound',NB_2c17_newburden) 
    i <- i:(i+2) 

但我不知道如何将其转换成蟒蛇

回答

1
df=pd.DataFrame({"col1":["one","two","three"],"col2":["four","five","six"],"col3":["seven","outbound","nine"],"col4":["ten","eleven","twelve"]}) 

for i in range(len(df.columns)): 
    if pd.Series.any(df.iloc[:,i].str.contains(pat="outbound")): 
     new_list=pd.DataFrame({df.columns[i-1]:df.iloc[:,i-1],df.columns[i]:df.iloc[:,i],df.columns[i+1]:df.iloc[:,i+1]}) 

print(new_list) 

    col2  col3 col4 
0 four  seven  ten 
1 five outbound eleven 
2 six  nine twelve 
+0

谢谢!!完美 –

+0

不客气! – 2Obe

相关问题