【问题标题】:Pandas make new column from string slice of another column熊猫从另一列的字符串切片创建新列
【发布时间】:2014-09-11 13:59:14
【问题描述】:

我想在 Pandas 中使用为数据框中的另一列切片的字符串创建一个新列。

例如。

Sample  Value  New_sample
AAB     23     A
BAB     25     B

其中New_sample 是由Sample 的简单[:1] 切片形成的新列

我尝试了很多方法都无济于事 - 我觉得我错过了一些简单的东西。

最有效的方法是什么?

【问题讨论】:

    标签: python pandas


    【解决方案1】:

    您可以调用str 方法并应用切片,这将比其他方法快得多,因为这是矢量化的(感谢@unutbu):

    df['New_Sample'] = df.Sample.str[:1]
    

    您也可以在 df 上调用 lambda 函数,但在较大的数据帧上会更慢:

    In [187]:
    
    df['New_Sample'] = df.Sample.apply(lambda x: x[:1])
    df
    Out[187]:
      Sample  Value New_Sample
    0    AAB     23          A
    1    BAB     25          B
    

    【讨论】:

      【解决方案2】:

      您也可以使用slice()Series 的字符串进行切片,如下所示:

      df['New_sample'] = df['Sample'].str.slice(0,1)
      

      来自pandas documentation

      Series.str.slice(start=None, stop=None, step=None)

      从系列/索引中的每个元素分割子字符串

      对于切片索引(如果索引是字符串类型),你可以试试:

      df.index = df.index.str.slice(0,1)
      

      【讨论】:

      • df.somecolumn.str[0:1]df.somecolumn.str.slice(0,1) 之间有什么偏好吗?
      【解决方案3】:

      为常见变化添加解决方案当切片宽度在 DataFrame Rows 中变化时

      #--Here i am extracting the ID part from the Email (i.e. the part before @)
      
      #--First finding the position of @ in Email
      d['pos'] = d['Email'].str.find('@')
      
      #--Using position to slice Email using a lambda function
      d['new_var'] = d.apply(lambda x: x['Email'][0:x['pos']],axis=1)
      
      #--Imagine x['Email'] as a string on which, slicing is applied
      

      希望这会有所帮助!

      【讨论】:

      • 感谢您添加这个常见的变体解决方案,正是我想要的!并合并成一行:d['new_var'] = d.apply(lambda x: x['Email'][0:x['Email'].find('@')],axis=1)
      猜你喜欢
      • 2023-02-05
      • 2023-01-07
      • 1970-01-01
      • 2020-12-27
      • 1970-01-01
      • 2022-07-06
      • 2020-07-11
      • 2018-08-15
      • 1970-01-01
      相关资源
      最近更新 更多