3

I need to fill a pandas dataframe column with empty numpy arrays. I mean that any row has to be an empty array. Something like

df['ColumnName'] = np.empty(0,dtype=float)

but this don't work because it tries to use every value of the array and assign one value per row.

I tried then

for k in range(len(df)):
     df['ColumnName'].iloc[k] = np.empty(0,dtype=float)

but still no luck. Any advice ?

5
  • 1
    Now, what do you mean by empty? Have you read the docs on np.empty? Commented Oct 27, 2017 at 13:12
  • I mean that every row of the dataframe has to contain an array object, unitialisated and of zero length. Commented Oct 27, 2017 at 13:14
  • 1
    Do simple search before asking stackoverflow.com/questions/31466769/… Commented Oct 27, 2017 at 14:55
  • What's the intended use of this column? That kind of array is pretty useless. Commented Oct 27, 2017 at 16:51
  • 1
    Possible duplicate of Add column of empty lists to DataFrame Commented Oct 28, 2017 at 2:53

2 Answers 2

2

You can repeat the np.empty into number of rows and then assign them to the column. Since it aint a scalar it cant be directly assigned like df['x'] = some_scalar.

df = pd.DataFrame({'a':[0,1,2]})

df['c'] = [np.empty(0,dtype=float)]*len(df)

Output :

  a   c
0  0  []
1  1  []
2  2  []
Sign up to request clarification or add additional context in comments.

3 Comments

Yes ! Thanks a lot
Glad to help. Dont forget to vote and accept the answer if it was helpful.
For some reason, this keeps making the lists dictionary for me. Might be to do with the version I am using of pandas/numpy, will check it out
2

You can also use a simple comprehension

df = pd.DataFrame({'a':[0,1,2]})
df['c'] = [[] for i in range(len(df))]

Output

   a   c
0  0  []
1  1  []
2  2  []

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.