【发布时间】:2018-12-20 06:36:08
【问题描述】:
我有一个数据框,其中一列包含列表。我正在尝试使用正则表达式过滤此列,但我得到的只是空数据框。
Source Length
0 [the sub-study process is over., EEE] 2
1 [Optional Pharma (DNA Research), Sub-Study inf... 2
2 [Sub-study ............................ 41] 1
我正在尝试过滤列表中“源列”在字符串末尾包含“(.*?)”的行(例如:1 [Optional Pharma (DNA Research), Sub-Study inf ... 2:此行在列表中第一个值的末尾有(DNA Research))使用下面的代码。
print(file_df.filter( regex=r'\(.*?\)\Z',axis=0))
输出是
Empty DataFrame
Columns: [ Source, Length]
Index: []
然后我尝试了这个,
print(file_df[file_df.Source.str.match('\(.*?\)\Z')])
为此我得到了
KeyError: '[nan nan] not in index'
谁能指出我的代码哪里出错了。
添加我的代码:
def sentence_process(file_df):
print(file_df.loc[file_df['Source'].str.contains(r'^[^,]*\([^()]*\)',regex= True)])
【问题讨论】:
-
试试
r'^[^,]*\([^()]*\)'。\Z模式匹配 Pythonre中字符串的末尾。 -
那么,你试过
file_df['Source'].str.contains(r'^[^,]*\([^()]*\)')吗?或者类似的东西? -
@WiktorStribiżew:我试过你的方法 file_df['Source'].str.contains(r'^[^,]*([^()]*)') 但我得到 NAN输出..
-
但是,如果我使用单个字符串尝试它会很好,但是当我使用数据框尝试它时,我会得到 NAN 值
-
试试
file_df[file_df['Source'].str.contains(r'^[^,]*\([^()]*\)')]
标签: python regex dataframe filter