【问题标题】:Separating a Pandas column after the nth time a unique character appears在第 n 次出现唯一字符后分离 Pandas 列
【发布时间】:2021-12-14 18:55:36
【问题描述】:

我正在尝试在 Pandas 中使用 ID 如下的列:

AB.156483.15645431.1561313513
CD.15615a.4651d15351.1512.1.21

我想创建一个新列,返回所有直到但不包括第二个期间的内容。

AB.156483.15645431
CD.15615a.4651d15351

我试过了:

pattern = r'([^.]*,[^,]*)'
df['test'] = df.ID.str.extract(pattern, expand=False)

并接收不可调用的字符串方法

我还尝试将单元格拆分为单元格内的列表,然后将列表转回字符串并使用列表理解重新插入句点:

df['test'] = ' '.join([str(item+'.') for item in [df.ID.str.split('.').str[0:3]]])

【问题讨论】:

  • 错字:您的pattern 有逗号,应该有句点。
  • 你不需要正则表达式。简单的字符串方法就可以了。像这样:'.'.join(s.split('.')[:3]),其中s 是列的内容。

标签: python regex pandas


【解决方案1】:

试试这个pattern:

df['test'] = df.ID.str.extract('^([^\.]+\.[^\.]+\.[^\.]+)')

或者用拆分:

df['test'] = (df['ID'].str.split('.',3, expand=True)
                .iloc[:,:3].agg('.'.join, axis=1)
             )

输出:

                               ID                  test
0   AB.156483.15645431.1561313513    AB.156483.15645431
1  CD.15615a.4651d15351.1512.1.21  CD.15615a.4651d15351

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-08-08
    • 2019-04-02
    • 1970-01-01
    • 1970-01-01
    • 2021-08-10
    • 1970-01-01
    • 2013-06-08
    相关资源
    最近更新 更多