pandas 从另一列的字符串切片中创建新列 [英] Pandas make new column from string slice of another column

查看:57
本文介绍了 pandas 从另一列的字符串切片中创建新列的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I want to create a new column in Pandas using a string sliced for another column in the dataframe.

例如.

Sample  Value  New_sample
AAB     23     A
BAB     25     B

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

Where New_sample is a new column formed from a simple [:1] slice of Sample

我尝试了许多尝试都无济于事-我觉得我缺少一些简单的东西.

I've tried a number of things to no avail - I feel I'm missing something simple.

最有效的方法是什么?

推荐答案

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

You can call the str method and apply a slice, this will be much quicker than the other method as this is vectorised (thanks @unutbu):

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

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

You can also call a lambda function on the df but this will be slower on larger dataframes:

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

这篇关于 pandas 从另一列的字符串切片中创建新列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆