有没有办法在 pandas 数据框的多列中修剪/剥离空格? [英] Is there a way to trim/strip whitespace in multiple columns of a pandas dataframe?
本文介绍了有没有办法在 pandas 数据框的多列中修剪/剥离空格?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个熊猫数据框,其中有5列,其中3列是字符串列。我想修剪那三列中的所有前导和尾随空格。有一种方法可以一次性实现。
I have a pandas dataframe with 5 columns and 3 of those columns are string columns. I want to trim all the leading and trailing whitespaces in those 3 columns. Is there a way to achieve this in one go.
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
I想修剪'col_1','col_2','col_4'
我知道 df ['col_1']。str.strip()
适用于单个列。但是我可以一次完成所有列吗?
I know df['col_1'].str.strip()
works on a individual column. But can i do all the columns at one go?
推荐答案
使用 DataFrame.apply
与列表列:
Use DataFrame.apply
with list of columns:
cols = ['col_1', 'col_2', 'col_4']
df[cols] = df[cols].apply(lambda x: x.str.strip())
或仅解析对象列,显然是字符串:
Or parse only object columns, it is obviously strings:
cols = df.select_dtypes(object).columns
df[cols] = df[cols].apply(lambda x: x.str.strip())
这篇关于有没有办法在 pandas 数据框的多列中修剪/剥离空格?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文