[英]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.