【问题标题】:Slice string in multiple column with same condition在具有相同条件的多列中切片字符串
【发布时间】:2021-05-27 17:54:01
【问题描述】:

我有多个列需要在相同条件下进行切片我可以看到一些解决方案 here 但它们不适用于多个列

df['x', 'y']=df['x', 'y'].str.slice(0,19)

错误

AttributeError: 'DataFrame' object has no attribute 'str'

【问题讨论】:

    标签: python string slice


    【解决方案1】:

    您需要使用apply 函数将其应用于多个列:

    df[['x','y']]=df[['x','y'].apply(lambda x:x.str.slice(0,19))
    

    它应该给出正确的输出。

    【讨论】:

      【解决方案2】:

      你可以使用applymap()方法

      import pandas as pd
      
      df_exp = pd.DataFrame([('ABCDEF', 'GHIJKL')], columns=["x", "y"])
      
      print(df_exp.head(10))
      #         x       y
      # 0  ABCDEF  GHIJKL
      
      your_slice_func = lambda x: x[0:3]
      df_result = df_exp.applymap(your_slice_func)
      
      print(df_result.head(10))
      #      x    y
      # 0  ABC  GHI
      
      

      【讨论】:

        猜你喜欢
        • 2017-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2017-02-15
        • 2020-11-27
        • 1970-01-01
        相关资源
        最近更新 更多