![](/img/trans.png)
[英]Merge columns and fill the empty space with the merged data using Pandas Python
[英]Remove space and newlines in pandas columns using idiomatic Python?
我使用下面的方法来替换pandas dataframe列标题中的所有空格和换行符。
我的问题是:
使用下面代码中的列表推导循环是一种更有效的方法吗?
def headerfiller(df):
for i in [" ","\n"]:
df.columns = [c.replace(i,"_") for c in df.columns]
您可以使用可用于索引对象的字符串方法,在本例中为columns.str.replace()
,它允许您在不自行循环值的情况下执行此操作:
In [23]: df = pd.DataFrame(np.random.randn(3,3), columns=['a\nb', 'c d', 'e\n f'])
In [24]: df.columns
Out[24]: Index([u'a\nb', u'c d', u'e\n f'], dtype='object')
In [25]: df.columns.str.replace(' |\n', '_')
Out[25]: Index([u'a_b', u'c_d', u'e__f'], dtype='object')
通过使用正则表达式,您可以同时替换空格和换行符。 请参阅文档: http : //pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.str.replace.html (对于Series,但方法与Index相同)
使用str.translate
:
>>> tbl = str.maketrans(' \n', '__')
>>> 'a b c\n'.translate(tbl)
'a_b_c_'
try:
tbl = str.maketrans('_ \n', '__') # Python 3.x
except AttributeError:
import string
tbl = string.maketrans('_ \n', '__') # Python 2.x
def headerfiller(df):
df.columns = [c.translate(tbl) for c in df.columns]
使用正则表达式替换:
>>> import re
>>> re.sub(r'[ \n]', '_', 'a b c\n')
'a_b_c_'
import re
def headerfiller(df):
df.columns = [re.sub(r' \n', '_', c) for c in df.columns]
你可以split()
和'_'.join()
:
def headerfiller(df):
df.columns = ['_'.join(c.split()) for c in df.columns]
它会丢失尾随空格和换行符(如果这很重要)并将多个空格等压缩为单个“_”:
In [26]: "_".join("a b c\n\n\n".split())
Out[26]: 'a_b_c'
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.