簡體   English   中英

熊貓從另一列的字符串切片創建新列

[英]Pandas make new column from string slice of another column

我想使用為數據框中另一列切片的字符串在 Pandas 中創建一個新列。

例如。

Sample  Value  New_sample
AAB     23     A
BAB     25     B

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

我嘗試了很多方法都無濟於事 - 我覺得我錯過了一些簡單的東西。

這樣做的最有效方法是什么?

您可以調用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

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

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

來自熊貓文檔

系列.str.slice(開始=無,停止=無,步驟=無)

從系列/索引中的每個元素切片子字符串

對於切片索引(如果索引是字符串類型),您可以嘗試:

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

當切片寬度跨 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

希望這可以幫助 !

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM