【发布时间】:2018-10-07 03:12:28
【问题描述】:
我正在尝试使用正则表达式来识别大熊猫数据框的特定行。具体来说,我打算将论文的 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,如上。
感谢所有帮助。谢谢。
【问题讨论】:
-
更改 test_doi 以转义括号后,查看过滤方法是否有效。即
test_doi = '0002-3568\(2004\)450'。另外,请参阅link 了解正确的正则表达式用法。