【问题标题】:Using regex to obtain the row index of a partial match within a pandas dataframe column使用正则表达式获取熊猫数据框列中部分匹配的行索引
【发布时间】: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 了解正确的正则表达式用法。

标签: python regex pandas


【解决方案1】:

您的第一种方法不起作用的原因有两个:

首先 - 如果您对系列使用 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 filter 函数过滤的是索引的标签,而不是值。

【讨论】:

    猜你喜欢
    • 2020-06-09
    • 2021-09-26
    • 2021-06-16
    • 2020-10-23
    • 2021-08-09
    • 1970-01-01
    • 2021-03-13
    • 1970-01-01
    • 2017-11-03
    相关资源
    最近更新 更多