1

Having a multi dimensional array, and I want to introduced as a column into a df.

import pandas as pd
import numpy as np

x = np.array([[1, 2, 3], [4, 5, 6]], np.int32)
df = pd.DataFrame(['A', 'B'], columns=['First'])

Initial df:

  First 
0     A 
1     B 

Final output should be:

  First  Second  
0     A   [1,2,3]
1     B   [4,5,6]

The final obj is to upload the table into a data base, and I understand is not the best way to keep records. If you have any recommendations are more than welcome.

Thanks.

2
  • 2
    df['second'] = [v for v in x] or df['second'] = list(x)... Commented Nov 27, 2019 at 16:58
  • list(x) did the trick thanks! Commented Nov 27, 2019 at 17:05

4 Answers 4

3

You can directly assign the array x by unpacking its rows into a list:

df.assign(second=[*x])

   First  second
0     A  [1, 2, 3]
1     B  [4, 5, 6]

Note that, as mentioned in the comments this is the same as:

df.assign(second=list(x))
Sign up to request clarification or add additional context in comments.

12 Comments

Let me add some details... @yuca
so is this a short hand for list comprehension? I get that you're calling a list over the contents of x, just wondering about the more technical detaiils
@Yuca same as df.assign(k=list(x))
Yes exactly @anky
@AlexSB except if you want to chain other operations (assign lets you do that), since assign() returns a copy whereas df[var]=.. is an inplace operation
|
2

Use:

df['Second']=x.tolist()
print(df)

  First     Second
0     A  [1, 2, 3]
1     B  [4, 5, 6]

Comments

1

Even though this will extend the length of table , I still recommend explode it , after groupby you can always convert it back.

Object data type in single columns will disable most of db query functions and pandas functions

df.assign(list=x.tolist()).explode('list')
Out[6]: 
  First list
0     A    1
0     A    2
0     A    3
1     B    4
1     B    5
1     B    6

Comments

1
 import pandas as pd
 import numpy as np

 x = np.array([[1, 2, 3], [4, 5, 6]], np.int32)
 df = pd.DataFrame(['A', 'B'], columns=['First'])
 df['second'] = [i for i in x] or df['second'] = list(x)
 print(df)

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.