从 pandas 的列中删除空间 [英] Removing space from columns in pandas

查看:20
本文介绍了从 pandas 的列中删除空间的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试从我拥有的数据框中删除空格.列名称如下所示.我试图去掉名字之间的空格,并在任何地方用_"替换它.

I am trying to remove spaces from a dataframe I have. The columns names look like below. I am trying to get the spaces between name out and replace it with "_" wherever present.

['join_date' 'fiscal_quarter' 'fiscal_year' 'primary_channel'
 'secondary_channel' 'customer_count' 'new_members' 'revisit_next_day'
 'revisit_14_day' 'demand_1yr' 'revisit_next_day_rate'
 'revisit_14_day_rate' 'demand_1yr_per_new_member' u'ch_Ad Network'
 u'ch_Affiliate' u'ch_Branded SEM' u'ch_DSP' u'ch_Daily Email'
 u'ch_Daily Messaging' u'ch_Direct' u'ch_Direct Publisher' u'ch_Email'
 u'ch_Feeds' u'ch_Native' u'ch_Non-Branded SEM' u'ch_Organic Search'
 u'ch_Paid Social' u'ch_Site' u'ch_Special Email' u'ch_Television'
 u'ch_Trigger Email' u'ch_UNMAPPED' u'ch_Unpaid Social' u'quarter_Q2'
 u'quarter_Q3' u'quarter_Q4']

推荐答案

  • 删除空格:
    1. 删除任何地方的空白:

    df.columns = df.columns.str.replace(' ', '')
    

    1. 删除字符串开头的空格:

    df.columns = df.columns.str.lstrip()
    

    1. 删除字符串末尾的空格:

    df.columns = df.columns.str.rstrip()
    

    1. 删除两端的空白:

    df.columns = df.columns.str.strip()
    

    • 用其他字符替换空格(例如下划线):
      1. 替换无处不在的空白

      df.columns = df.columns.str.replace(' ', '_')
      

      1. 替换开头的空格:

      df.columns = df.columns.str.replace('^ +', '_')
      

      1. 替换末尾的空格:

      df.columns = df.columns.str.replace(' +$', '_')
      

      1. 替换两端的空白:

      df.columns = df.columns.str.replace('^ +| +$', '_')
      


      以上所有内容也适用于特定列,假设您有一个名为 col 的列,然后执行:

      df[col] = df[col].str.strip()  # or .replace as above
      


      命令可以链接


      Commands can be chained

      df.columns = df.columns.str.strip().str.replace(' ', '_')
      

      这篇关于从 pandas 的列中删除空间的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆