3

We have a dataframe where the elements of one column are lists (the discussion is not about if this should be done or not). A simple example is the following:

df = pd.DataFrame([[12,[123,234,234]], [14,[124,25,235]], [16,[1267,267,2345]]], columns = ['A', 'B'])

obtaining:

enter image description here

the goal here to to convert the column B into a numpy array, like the following one:

enter image description here.

If I ask to pandas convert the column into an array:

df['B'].values

it returns an array of list, which is not the same as the one above:

array([list([123, 234, 234]), list([124, 25, 235]),
   list([1267, 267, 2345])], dtype=object)

How can we solve the problem?

1 Answer 1

2

If always same length of lists is possible create nested lists and then convert to np.array:

arr = np.array(df['B'].values.tolist())
#alternative
#arr = np.array(df['B'].tolist())
print (arr)
[[ 123  234  234]
 [ 124   25  235]
 [1267  267 2345]]
Sign up to request clarification or add additional context in comments.

Comments

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.