【问题标题】:Return the index/position of the first digit/letter in a string in Pandas Dataframe返回 Pandas Dataframe 中字符串中第一个数字/字母的索引/位置
【发布时间】:2020-08-25 23:43:55
【问题描述】:

我有一个包含几列的数据框。其中之一是df['col1'],其字符串值由字母、特殊字符(. 或 _)和数字组成。我想创建一个返回索引 + 1 或第一位数字或 alpha 的位置的新列。

我知道这不起作用,但类似:

df['new_col'] = df['col1'].apply(lambda x: re.search(r'\d', str(x))).str.startswith()

这样

col1 = abc12 returns 4, 
33zxy returns 1, 
hi_world2 returns 9 

以此类推(如果是第一个数字的位置)。

我也尝试过使用 find、next 和 filter,但它们不起作用。

df['new_col'] = df['col1'].str.find(next(filter(str.isalpha, df['col1']))) + 1

任何帮助将不胜感激!

【问题讨论】:

    标签: python python-3.x regex pandas dataframe


    【解决方案1】:

    你可以使用 re.search

    import re
    df['col1'].apply(lambda x: re.search('\d+', x).start()) + 1
    

    你得到

    0    4
    1    1
    2    9
    

    编辑:如果没有匹配,re.search().start() 将抛出属性错误。这需要有条件地处理。由于 Pandas 将 NaN 解释为浮点数,因此结果位置将是浮点类型

    df = pd.DataFrame({'col1':['abc12', '33zxy', 'hi_world2','abc']})
    
    df['col1'].apply(lambda x: re.search('\d+', x).start() if re.search('\d+', x) else re.search('\d+', x)) + 1
    
    0    4.0
    1    1.0
    2    9.0
    3    NaN
    

    【讨论】:

    • 首先感谢您的帮助!但是,我收到一个 AttributeError 说 NoneType 对象没有属性“开始”。你知道如何解决这个问题吗?
    • 啊,没想到。现在可以了!非常感谢。
    • @casi_cielo32,如果这解决了您的问题,您可以接受答案
    • 你知道如何获取字符串中“第二个”大写字母的位置吗?我试过 df['col2'].apply(lambda x: re.search("[A-Z]"{2}, x).span()[1] if re.search("[A-Z]"{2}, x) else re.search("[A-Z]"{2}, x)) + 1```,但它不起作用。
    猜你喜欢
    • 2013-10-02
    • 1970-01-01
    • 1970-01-01
    • 2015-05-22
    • 2016-07-06
    • 2015-08-31
    • 1970-01-01
    • 1970-01-01
    • 2011-01-23
    相关资源
    最近更新 更多