【问题标题】:Copy text between parentheses in pandas DataFrame column into another column将 pandas DataFrame 列中括号之间的文本复制到另一列
【发布时间】:2013-05-26 08:56:53
【问题描述】:

我正在尝试将出现在 pandas DataFrame 列中括号之间的文本复制到另一列中。我遇到了这个解决方案来相应地解析字符串:Regular expression to return text between parenthesis

我想将结果逐个元素分配给新列中的同一行。 但是,这不会直接延续到 pandas 系列。我似乎 map/apply/lambda 似乎是要走的路。我已经到达了这段代码,但是遇到了无效的语法错误。

dataSources.dataUnits = dataSources.dataDescription.map(str.find("(")+1:str.find(")"))

显然,我在那里还不够流利 - 非常感谢您的帮助。

【问题讨论】:

    标签: python string pandas dataframe


    【解决方案1】:

    您可以使用 there 建议的相同方法进行申请:

    In [11]: s = pd.Series(['hi(pandas)there'])
    
    In [12]: s
    Out[12]:
    0    hi(pandas)there
    dtype: object
    
    In [13]: s.apply(lambda st: st[st.find("(")+1:st.find(")")])
    Out[13]:
    0    pandas
    dtype: object
    

    或者也许您可以使用 Series 字符串方法之一,例如replace:

    In [14]: s.str.replace(r'[^(]*\(|\)[^)]*', '')
    Out[14]:
    0    pandas
    dtype: object
    

    扔掉(之前的所有东西和)之后的所有东西。

    从 0.13 开始你可以使用extract 方法:

    In [15]: s.str.extract('.*\((.*)\).*')
    Out[15]: 
    0    pandas
    dtype: object
    

    【讨论】:

    • 非常感谢,正是我需要的!
    • 只有一个问题:没有括号内容的行返回整个字段(字段用''括起来)。如何避免这种情况/跳过没有找到的行?
    • 嗯,不太确定,认为您可能只使用 apply 会更好,但使用 match 的东西是可能的:s.str.findall(r'(?<=\()[^(]*(?=\))')
    • @MegaBytes 可能使用 \d+ 而不是 [^(]*
    • 谢谢@AndyHayden 我用了这个对我有用的data['Title'].str.extract('.*\((.*\d{4})\).*')
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-26
    • 2020-06-16
    • 1970-01-01
    • 2017-02-15
    • 1970-01-01
    相关资源
    最近更新 更多