有没有办法修剪/去除 pandas 数据帧的多列中的空格?

Ris*_*Sun 9 python string dataframe pandas

我有一个包含 5 列的 pandas 数据框,其中 3 列是字符串列。我想修剪这 3 列中的所有前导和尾随空格。有没有一种方法可以一次性实现这一目标。

  ID    col_1  col_2    col_3   col_4
0  1      AA     XX      200     PP
1  2      BB     YY      300     QQ
2  3      CC     ZZ      500     RR
Run Code Online (Sandbox Code Playgroud)

我想修剪'col_1', 'col_2', 'col_4'

我知道df['col_1'].str.strip()在一个单独的专栏上工作。但我可以一次性完成所有列吗?

jez*_*ael 21

DataFrame.apply与列列表一起使用:

cols = ['col_1', 'col_2', 'col_4']
df[cols] = df[cols].apply(lambda x: x.str.strip())
Run Code Online (Sandbox Code Playgroud)

或者只解析对象列,它显然是字符串:

cols = df.select_dtypes(object).columns
df[cols] = df[cols].apply(lambda x: x.str.strip())
Run Code Online (Sandbox Code Playgroud)