从 pandas 中的数据框列中删除空间 [英] Removing space from dataframe columns in pandas
本文介绍了从 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(' ', '')
2)要删除字符串开头的空白:
df.columns = df.columns.str.lstrip()
3)要删除字符串末尾的空白:
df.columns = df.columns.str.rstrip()
4)删除两端处的空白:
df.columns = df.columns.str.strip()
- 用其他字符替换空格 (例如,下划线):
5)替换空白无处不在
df.columns = df.columns.str.replace(' ', '_')
6)要在开始处替换空白 :
6) To replace white space at the beginning:
df.columns = df.columns.str.replace('^ +', '_')
7)最后替换空白 :
df.columns = df.columns.str.replace(' +$', '_')
8)替换两端的空白 :
8) To replace white space at both ends:
df.columns = df.columns.str.replace('^ +| +$', '_')
以上所有内容也适用于特定列,假设您有一个名为col
的列,则只需执行以下操作即可:
All above applies to a specific column as well, assume you have a column named col
, then just do:
df[col] = df[col].str.strip() # or .replace as above
这篇关于从 pandas 中的数据框列中删除空间的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文