【问题标题】:Is there a way to trim/strip whitespace in multiple columns of a pandas dataframe?有没有办法在熊猫数据框的多列中修剪/去除空白?
【发布时间】:2019-10-08 13:30:33
【问题描述】:

我有一个包含 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

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

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

【问题讨论】:

    标签: python string pandas dataframe


    【解决方案1】:

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

    cols = ['col_1', 'col_2', 'col_4']
    df[cols] = df[cols].apply(lambda x: x.str.strip())
    

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

    cols = df.select_dtypes(object).columns
    df[cols] = df[cols].apply(lambda x: x.str.strip())
    

    【讨论】:

      【解决方案2】:

      df.columns = df.columns.str.strip()

      【讨论】:

      • OP 想要剥离列,而不是列名
      • 这个答案对我很有用,因为我确实想去掉列名。非常感谢你,格雷!
      猜你喜欢
      • 2020-07-14
      • 1970-01-01
      • 2021-12-10
      • 2017-08-28
      • 2021-04-10
      • 1970-01-01
      • 2022-10-12
      • 2017-05-23
      • 2019-06-29
      相关资源
      最近更新 更多