0
import numpy as np

import pandas as pd

a=np.array(['ma_ya','dj_kh','ja_aa'])

a1=(lambda x:x[0].split('_'),a)
a1

output:

 (<function __main__.<lambda>>, array(['ma_ya', 'dj_kh', 'ja_aa'], 
       dtype='<U5'))

i want the output to be ['ma','dj','ja'] using lambda function. kindly help

1
  • 2
    Does it need to use numpy for some reason? Otherwise a1 = map(lambda x: x.split('_')[0] , a) should work Commented Jul 2, 2020 at 7:42

6 Answers 6

1
a1 = list(map(lambda x: x.split('_')[0], a))   
Sign up to request clarification or add additional context in comments.

Comments

1

As a is a np.array, you can use list comprehension

a1 = [x.split('_')[0] for x in a]

Outputs: ['ma', 'dj', 'ja']

Comments

0
a1 = list(map(lambda x: x.split("_")[0], a))

print(a1)

Output:

['ma', 'dj', 'ja']

Comments

0

Alternatively, use pd.Series:

a1=pd.Series(a).apply(lambda x:x.split('_')[0])

result:

0    ma
1    dj
2    ja
dtype: object

or convert to list:

a1=list(pd.Series(a).apply(lambda x:x.split('_')[0]))

output:

['ma', 'dj', 'ja']

Comments

0

Hey you can use list comprehension instead of using lambda as shown here

import numpy as np
import pandas as pd
a=np.array(['ma_ya','dj_kh','ja_aa'])
a1=[i.split('_')[0] for i in a]
print(a1)

Output : ['ma', 'dj', 'ja']

3 Comments

How is this different to answer?. This actually borders plagiarism.
I was writing this answer and till then the same answer was already posted.I didn't check then.
Yes, that's true, it usually happens, but now that you realize that the answer had already been published, the best thing would be to edit it to give a different answer or delete it, otherwise it could be considered plagiarism.
0

Using list-comprehension:

s = ['ma_ya','dj_kh','ja_aa']

print([x.split('_')[0] for x in s])

OUTPUT:

['ma','dj','ja']

1 Comment

How is this different to answer?. This actually borders plagiarism.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.