Error: create a column from an existing array

Hello everyone,

I’m trying to add a new column (in the first position) to an existing DataFrame (df) from an existing array (members) but when I run insertcols!(df,1, :Members =>members), it show me following error:

ArgumentError: adding AbstractArray other than AbstractVector as a column of a data frame is not allowed

Stacktrace:
 [1] insertcols!(::DataFrame, ::Int64, ::Pair{Symbol,Array{String,2}}; makeunique::Bool, copycols::Bool) at /Users/pablogalaz/.julia/packages/DataFrames/kwVTY/src/dataframe/dataframe.jl:760
 [2] insertcols!(::DataFrame, ::Int64, ::Pair{Symbol,Array{String,2}}) at /Users/pablogalaz/.julia/packages/DataFrames/kwVTY/src/dataframe/dataframe.jl:721
 [3] top-level scope at In[44]:1

I already try to do this with other df-array and it works very well. The rest of the code here:

members = ["Belen" "Lau" "Javi" "Joaco" "Nico" "Rodrigo" "Vicente" "Pablo" "Falcao" "Montse"]

df = 
Row	Lunes	Martes	Miercoles	Jueves	Viernes	Sabado	Domingo
    Int64	Int64	Int64	    Int64	Int64	Int64	Int64
1	0	    0	    1 	        0	    0	    -1	       -1
2	1	    0	    0	        0	    1	    -1	       -1
3	0	    0	    1	       -1	    0	    -1	        1
4	1	    0	    0	        1	    1	    -1	       -1
5	1	    1	    0	       -1	    0	     1	       -1
6	0	    1	    0	       -1	    1	     1	       -1
7	0	    1	    0	       -1	    1	    -1	        1
8	1	    1	    0	        1	    0	    -1	       -1
9	0	    0	    1	        1	   -1	     1	       -1
10	0	    0	    1	        1	   -1	    -1  	    1

insertcols!(df,1, :Members =>members) #ERROR

1 Like

it worked when i added commas between the strings:

using DataFrames
df = dataframe(a = rand(10))  
members = ["Belen","Lau","Javi","Joaco","Nico","Rodrigo","Vicente","Pablo","Falcao","Montse"]
julia> insertcols!(df,1, :Members =>members)
10×2 DataFrame
│ Row │ Members │ a         │        
│     │ String  │ Float64   │        
├─────┼─────────┼───────────┤
│ 1   │ Belen   │ 0.5535    │        
│ 2   │ Lau     │ 0.696888  │
│ 3   │ Javi    │ 0.285581  │        
│ 4   │ Joaco   │ 0.503806  │        
│ 5   │ Nico    │ 0.305051  │        
│ 6   │ Rodrigo │ 0.0708788 │        
│ 7   │ Vicente │ 0.268658  │
│ 8   │ Pablo   │ 0.14032   │        
│ 9   │ Falcao  │ 0.517392  │        
│ 10  │ Montse  │ 0.264026  │        

the problem seems to stem from the fact that you were trying to add a row of names as it was a column. but adding the commas solves the problem.
Other option,that works for your original input:

insertcols!(df,1, :Members =>vec(members)) #reinterprets the Array as a vector
2 Likes

The vec() function was the solve! Thank you

1 Like