Lor*_*cán 2 python regex 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'
Run Code Online (Sandbox Code Playgroud)
在此示例中,我希望能够通过在 ScID.xml 列中查找部分匹配来返回第三行 (2) 的索引。DOI 并不总是位于 ScID.xml 字符串的开头。
我搜索了该网站并应用了针对类似场景描述的方法。
包括:
df.iloc[:,0].apply(lambda x: x.contains(test_doi)).values.nonzero()
Run Code Online (Sandbox Code Playgroud)
这将返回:
AttributeError: 'str' object has no attribute 'contains'
Run Code Online (Sandbox Code Playgroud)
和:
df.filter(regex=test_doi)
Run Code Online (Sandbox Code Playgroud)
给出:
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]
Run Code Online (Sandbox Code Playgroud)
最后:
df.loc[:, df.columns.to_series().str.contains(test_doi).tolist()]
Run Code Online (Sandbox Code Playgroud)
它也返回Empty DataFrame如上所述。
感谢所有帮助。谢谢。
您的第一种方法不起作用的原因有两个:
首先 - 如果您对系列使用 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
Run Code Online (Sandbox Code Playgroud)
顺便说一句,pandas 过滤函数过滤索引的标签,而不是值。