Python – Pandas make new column from string slice of another column


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

For example.

Sample  Value  New_sample
AAB     23     A
BAB     25     B

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.

What's the most efficient way of doing this?

Best Answer

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]

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])
  Sample  Value New_Sample
0    AAB     23          A
1    BAB     25          B