【问题标题】:Check the string is ending with "|" using python检查字符串是否以“|”结尾使用蟒蛇
【发布时间】:2022-01-25 12:53:38
【问题描述】:

我需要检查字符串是否以|结尾。

Student,"Details"
Joe|"December 2017|maths"
Bob|"April 2018|History|Biology|Physics|"
sam|"December 2018|physics"

我已尝试使用以下代码,但它没有按预期工作。

def Pipe_in_variant(path):
    df = pd.read_csv(path, sep='|')
    mask = (df['Details'])
    result = mask.endswith(""|"")
    print("...................")
    print(result)

【问题讨论】:

    标签: python pandas


    【解决方案1】:

    您的示例输入不清楚,但是假设您要检查列中的项目是否以某些内容结尾,请使用str.endswith

    例子:

    df = pd.DataFrame({'Details': ['ab|c', 'acb|']})
    
    df['Details'].str.endswith('|')
    

    输出:

    0    False
    1     True
    Name: Details, dtype: bool
    
    打印匹配的行:
    df[df['Details'].str.endswith('|')]
    

    输出:

      Details
    1    acb|
    

    【讨论】:

    • 是否可以在此处打印匹配行:Bob|"April 2018|History|Biology|Physics|"
    • @Sreerag 当然,请参阅更新的答案
    • 我已根据建议进行了更改,但它再次对我不起作用。 df = pd.read_csv(path, sep='|') dd = df.DataFrame({'Details': ['ab|c', 'acb|']}) mask=dd[dd['Details']。结尾('|')] 打印(dd[掩码])
    • @Daniel Walker:非常适合我。
    【解决方案2】:

    注意 - 我认为输入的第一行应该是 Student|"Details" 而不是 Student,"Details"

    你可以这样做

    import pandas as pd
    dframe = pd.read_csv('input.txt', sep='|')
    dframe['ends_with_vbar'] = dframe['Details'].str.endswith('|')
    dframe
    

    输出:

      Student                              Details  ends_with_vbar
    0     Joe                  December 2017|maths           False
    1     Bob  April 2018|History|Biology|Physics|            True
    2     sam                December 2018|physics           False
    

    然后你可以打印标记的行如下

    for _, row in dframe[dframe['ends_with_vbar']].iterrows():
        print(f'{row["Student"]} - {row["Details"]}')
    

    输出:

    Bob - April 2018|History|Biology|Physics|
    

    【讨论】:

    • 完美运行
    • 在这样的任务上使用 iterrows 不是一个好的解决方案。最好直接选择所有满足条件的条目,一次输出。
    • iterrows 在使用dframe[dframe['ends_with_vbar']]进行选择后完成
    • 有什么办法可以检查上述输入的空字符串或空值。
    • 您可以在执行endswith 之前使用dframe = dframe[dframe['Detaisl'].isnull() == False] 过滤掉空行
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-08-20
    • 2013-08-23
    • 1970-01-01
    • 2015-09-16
    • 1970-01-01
    • 2022-08-21
    相关资源
    最近更新 更多