我想在Pandas中创建一个新列,使用为数据帧中的另一列切片的字符串.
例如.
Sample Value New_sample
AAB 23 A
BAB 25 B
Run Code Online (Sandbox Code Playgroud)
New_sample从一个简单的[:1]切片形成的新列在哪里Sample
我尝试过很多东西都无济于事 - 我觉得我错过了一些简单的东西.
这样做最有效的方法是什么?
EdC*_*ica 51
你可以调用str方法并应用一个切片,这比其他方法快得多,因为这是矢量化的(感谢@unutbu):
df['New_Sample'] = df.Sample.str[:1]
Run Code Online (Sandbox Code Playgroud)
你也可以在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
Run Code Online (Sandbox Code Playgroud)
stu*_*ent 10
您还可以使用以下方式slice()对字符串进行切片Series:
df['New_sample'] = df['Sample'].str.slice(0,1)
Run Code Online (Sandbox Code Playgroud)
来自熊猫文档:
系列.str.slice(开始=无,停止=无,步骤=无)
从系列/索引中的每个元素切片子字符串
对于切片索引(如果索引是字符串类型),您可以尝试:
df.index = df.index.str.slice(0,1)
Run Code Online (Sandbox Code Playgroud)
小智 8
当切片宽度跨 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
Run Code Online (Sandbox Code Playgroud)
希望这可以帮助 !
| 归档时间: |
|
| 查看次数: |
47958 次 |
| 最近记录: |