【问题标题】:Python : how to extract the first substring of a string with separator into another column?Python:如何将带分隔符的字符串的第一个子字符串提取到另一列中?
【发布时间】:2022-01-07 15:03:12
【问题描述】:

我有一个数据框,其中有一列“CCR”,其值如下: “Aaaa;Bbbb;Cccc”或“Bbbb;;Cccc”或“Cccc;Bbbb;Aaaa”。 我只想取第一部分(在“;”之前)并将其放入另一列“1st CCR”。我似乎无法使用 split 功能使其工作。使用此代码我尝试过,没有任何反应。 你能帮忙吗?

def get_1stCCR(row):
  for row in df['CCR']:
    df['1stCCR'] = row.split(";")[0]

df['CCR'].apply(get_1stCCR)

【问题讨论】:

    标签: python split delimiter separator


    【解决方案1】:

    您可以使用 lambda 函数执行以下操作:

    df['newCCR']=df['CCR'].apply(lambda x:x[0:x.index(';')])
    

    如果某些行没有';'在其中,您应该使用:

    df['newCCR']=df['CCR'].apply(lambda x:x[0:x.index(';') if ';' in x else None])
    

    【讨论】:

    • 我收到“ValueError: substring not found”。
    • @Heltal 是否有可能并非所有值都有“;”在他们里面?
    • 确实,有些只有一个值,因此没有';'一点也不。在这种情况下,我想提取该值。
    • 非常感谢!如果我正在寻找一个特定的子字符串(例如“ABC”)放入我的辅助列,我将如何更改这个 lambda 函数? df['newCCR']=df['CCR'].apply(lambda x:x[0:x.index(';') if 'ABC' in x else None])
    猜你喜欢
    • 2018-12-13
    • 1970-01-01
    • 2020-09-20
    • 2019-07-07
    • 2020-02-01
    • 2017-03-13
    • 2022-01-04
    • 1970-01-01
    相关资源
    最近更新 更多