使用正则表达式获取pandas dataframe列中部分匹配的行索引

时间:2018-04-26 12:09:43

标签: python regex pandas

我正在尝试使用正则表达式来识别大型pandas数据帧的特定行。具体来说,我打算将论文的DOI与包含DOI号的xml ID相匹配。

# An example of the dataframe and a test doi:

                                    ScID.xml     journal  year    topic1
0    0009-3570(2017)050[0199:omfg]2.3.co.xml  Journal_1   2017  0.000007
1  0001-3568(2001)750[0199:smdhmf]2.3.co.xml  Journal_3   2001  0.000648
2  0002-3568(2004)450[0199:gissaf]2.3.co.xml  Journal_1   2004  0.000003
3  0003-3568(2011)150[0299:easayy]2.3.co.xml  Journal_1   2011  0.000003

# A dummy doi:

test_doi = '0002-3568(2004)450'

在这个示例中,我希望能够通过在ScID.xml列中找到部分匹配来返回第三行(2)的索引。 DOI并不总是在ScID.xml字符串的开头。

我搜索了这个网站并应用了针对类似场景描述的方法。

,包括:

df.iloc[:,0].apply(lambda x: x.contains(test_doi)).values.nonzero()

返回:

AttributeError: 'str' object has no attribute 'contains'

df.filter(regex=test_doi)

给出:

Empty DataFrame

Columns: []
Index: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 
19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36,
37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 
55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 
73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 
91, 92, 93, 94, 95, 96, 97, 98, 99, ...]

[287459 rows x 0 columns]

最后:

df.loc[:, df.columns.to_series().str.contains(test_doi).tolist()]

也会返回Empty DataFrame,如上所述。

感谢所有帮助。谢谢。

1 个答案:

答案 0 :(得分:3)

为什么第一种方法不起作用有两个原因:

首先 - 如果对一个系列使用apply,则lambda函数中的值将不是一个序列而是一个标量。并且因为contains是来自pandas而不是来自字符串的函数,所以你会收到错误消息。

第二 - 括号在正则表达式中具有特殊含义(划分捕获组)。如果你想把括号作为字符,你必须逃避它们。

test_doi = '0002-3568\(2004\)450'
df.loc[df.iloc[:,0].str.contains(test_doi)]
                                    ScID.xml    journal  year    topic1
2  0002-3568(2004)450[0199:gissaf]2.3.co.xml  Journal_1  2004  0.000003

再见,pandas过滤函数过滤索引的标签,而不是值。