【问题标题】:Regular expression to rename the column by stripping the column name通过剥离列名来重命名列的正则表达式
【发布时间】:2020-07-05 09:33:24
【问题描述】:

我的 df 有很多列,每列都有重复的值,因为它的调查数据。例如,我的数据如下所示:

df:

 Q36r9: sales platforms - Before purchasing a new car         Q36r32: Advertising letters - Before purchasing a new car
        Not Selected                                                                         Selected

所以我想从列名中删除文本。例如,我想从第一列获取“:”和“-”之间的文本。所以它应该是这样的:“销售平台”,在第二部分我想转换列的值,“选择”应该用列的名称和“未选择”更改为 NaN

所以想要的输出应该是这样的:

sales platforms                                       Advertising letters
      NaN                                             Advertising letters

已编辑:如果我的列名如下:

Q40r1c3: WeChat - Looking for a new car - And now if you think again  - Which social media platforms or sources would you use in each situation?

如果我只想在“:”和“-”之间找到一些东西。它应该提取“微信”

【问题讨论】:

    标签: python pandas rename strip


    【解决方案1】:

    IIUC,

    我们可以利用.* 的一些正则表达式和贪婪匹配,它匹配定义的模式之间的所有内容

    import re
    
    df.columns = [re.search(':(.*)-',i).group(1) for i in df.columns.str.strip()]
    
    print(df.columns)
    
       sales platforms   Advertising letters 
    0      Not Selected                  None
    

    编辑:

    通过贪心匹配我们可以使用+?

    +? Quantifier — Matches between one and unlimited times, as few times as possible, expanding as needed (lazy)
    

    Q36r9: sales platforms - Before purchasing a new car    Q40r1c3: WeChat - Looking for a new car - And now if you think again - Which social media platforms or sources would you use in each situation?
    0                                                       1
    
    
    import re
    
    [re.search(':(.+?)-',i).group(1).strip() for i in df.columns]
    
    ['sales platforms', 'WeChat']
    

    【讨论】:

    • 是否有任何正则表达式可以让我们在第一场比赛中停下来?例如,上面的代码在“-”出现一次时正常运行,但当它出现超过 1 时,它会捕获“:”和最后一个“-”之间的所有内容
    • @s_khan92 你能用示例字符串编辑你的问题吗?
    • 我编辑了@Datanovice.. 如果我只想获取字符串微信?
    • 谢谢@Datanovice :)
    猜你喜欢
    • 2020-12-07
    • 2021-08-27
    • 2021-11-04
    • 2018-05-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-11-29
    • 2014-04-03
    相关资源
    最近更新 更多