1

I have a column in pandas dataframe which has items like following,

SubBrand
Sam William Mathew
Jonty Rodes
Chris Gayle

I want to create a new column (SubBrand_new) such as

  SubBrand_new
0 SWM
1 JR
2 CG

I am using this piece of code,

df1["SubBrand_new"] = "".join([x[0] for x in (df1["SubBrand"].str.split())])

but not able to get what I am looking for. Can anybody help?

2 Answers 2

4

We can do split with expand and sum i.e

df['SubBrand'].str.split(expand=True).apply(lambda x : x.str[0]).fillna('').sum(1)

0    SWM
1     JR
2     CG
dtype: object
3
  • 1
    ha-ha, i had exactly the same version: df.SubBrand.str.split(expand=True).apply(lambda c: c.str[0]).fillna('').sum(1), but you were faster :-D Dec 6, 2017 at 14:31
  • 2
    I had df['Abbrev'] = df['Name'].str.split(expand=True).apply(lambda x: x.str[0]).apply(''.join) but I think this is nicer +1
    – EdChum
    Dec 6, 2017 at 14:32
  • @EdChum my first solution was that since there were None I went for sum Dec 6, 2017 at 14:34
2

You want to apply a function to every line and return a new column with its result. This kind of operation can be applied with the .apply() method, a simple = attribution will not do the trick. A solution in the spirit of your code would be:

df = pd.DataFrame({'Name': ['Marcus Livius Drussus',
                            'Lucius Cornelius Sulla',
                            'Gaius Julius Caesar']})
df['Abrev'] = df.Name.apply(lambda x: "".join([y[0] for y in (x.split())]))

Which yields

df
    Name                    Abrev
0   Marcus Levius Drussus   MLD
1   Lucius Cornelius Sulla  LCS
2   Gaius Julius Caesar     GJC

EDIT:

I compared it to the other solution, thinking that the apply() method with join() would be pretty slow. I was surprised to find that it is in fact faster. Setting:

N = 3000000
bank = pd.util.testing.rands_array(3,N)
vec = [bank[3*i] + ' ' + bank[3*i+1] + ' ' + bank[3*i+2]  for i in range(N/3)]
df = pd.DataFrame({'Name': vec})

I find:

df.Name.apply(lambda x: "".join([y[0] for y in (x.split())]))
executed in 581ms

df.Name.str.split(expand=True).apply(lambda x : x.str[0]).fillna('').sum(1)
executed in 2.81s
3
  • If there are 2 different names for which Abrev are coming as same, how to tackle that scenario? Dec 6, 2017 at 14:46
  • What do you want for output if you have names with the same initials?
    – Ricardo
    Dec 6, 2017 at 14:52
  • 1
    In fact list comprehension was what came to my mind when I saw the question, my way is a pandas way of doing it, since we expand it is a lot lot slower Dec 6, 2017 at 15:00

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.