2

Can I do the following conversion to an array, using constructs like df.col.apply(lambda x ... , without using 'traditional' for-loops (one iterating over the columns and another iterating over words within each column's string value)?

All my attempts gave error messages like The truth value of an array with more than one element is ambiguous. Use a.any() or a.all().

Example:

d = {'foo' : [1,2,3], 'bar': [-2,-2,-3]}
df = pd.DataFrame({'col': ['foo mur bar','foo','mur mur']}, index=[1,2,3])

Expected output is:

np.array([
    [[1,2,3],[-2,-2,-3]],
    [[1,2,3]],
    [[]]
])
2

1 Answer 1

1

Try using:

a = df['col'].str.split().apply(lambda x: pd.Series(x).map(d)).values
a = np.array([pd.Series(i).dropna().values for i in a])
print(a)

Output:

[array([[1, 2, 3], [-2, -2, -3]], dtype=object)
 array([[1, 2, 3]], dtype=object) array([], dtype=object)]
Sign up to request clarification or add additional context in comments.

1 Comment

thank you. I could do it by np.array(df1.col.apply(lambda x: np.array([d[item] for item in x.split(' ') if d.get(item, 0) != 0]))) but you way more quickly imho.

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.