使用惯用的Python删除pandas列中的空格和换行符?

Alo*_*uri 3 python list-comprehension dataframe pandas

我使用下面的方法来替换 pandas 数据框列标题中的所有空格和换行符。

我的问题是:

在下面的代码中使用列表理解是一种更有效的循环方法吗?

def headerfiller(df):
    for i in [" ","\n"]:
        df.columns = [c.replace(i,"_") for c in df.columns]
Run Code Online (Sandbox Code Playgroud)

jor*_*ris 5

您可以使用可用于索引对象的字符串方法,在这种情况下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')
Run Code Online (Sandbox Code Playgroud)

通过使用正则表达式,您可以同时替换空格和换行符。请参阅文档:http://pandas.pydata.org/pandas-docs/stable/ generated/pandas.Series.str.replace.html(对于Series,但方法与Index相同)