Convert List of Vectors to Data Frame

convert a list of vectors to data frame

An option with base R

do.call(rbind, Map(cbind, lapply(a, stack), P = names(a)))

Convert a list to a data frame

Update July 2020:

The default for the parameter stringsAsFactors is now default.stringsAsFactors() which in turn yields FALSE as its default.


Assuming your list of lists is called l:

df <- data.frame(matrix(unlist(l), nrow=length(l), byrow=TRUE))

The above will convert all character columns to factors, to avoid this you can add a parameter to the data.frame() call:

df <- data.frame(matrix(unlist(l), nrow=132, byrow=TRUE),stringsAsFactors=FALSE)

Use bind_rows to convert list of vectors to dataframe

One option could be:

map_dfr(a, ~ set_names(.x, paste0("V", seq_along(.x))))

V1 V2 V3 V4
<dbl> <dbl> <dbl> <dbl>
1 1 2 3 4
2 1 2 3 4
3 4 5 6 3
4 6 3 2 6

Convert list of raw-vectors in dataframe

You have to use I when creating the data.frame.

output <- list(raw(2), raw(3))
DF <- data.frame(ID=1:2, vectors = I(output))

str(DF)
#'data.frame': 2 obs. of 2 variables:
# $ ID : int 1 2
# $ vectors:List of 2
# ..$ : raw 00 00
# ..$ : raw 00 00 00
# ..- attr(*, "class")= chr "AsIs"

DF
#DF
# ID vectors
#1 1 00, 00
#2 2 00, 00, 00

How do you convert large list with vectors of different lenght to dataframe?

You could do:

t(as.data.frame(lapply(lst, "length<-", max(lengths(lst)))))

# [,1] [,2] [,3] [,4] [,5]
#a 1 2 4 5 6
#c 7 8 9 NA NA
#c.1 10 11 NA NA NA

Or as @Andrew pointed out, you can do:

t(sapply(lst, "length<-", max(lengths(lst))))

# [,1] [,2] [,3] [,4] [,5]
#a 1 2 4 5 6
#c 7 8 9 NA NA
#c 10 11 NA NA NA

Convert list of arrays to pandas dataframe

Option 1:

In [143]: pd.DataFrame(np.concatenate(list_arrays))
Out[143]:
0 1 2 3 4 5 6 7 8
0 0 0 0 1 0 0 0 0 0
1 0 0 3 2 0 0 0 0 0

Option 2:

In [144]: pd.DataFrame(list(map(np.ravel, list_arrays)))
Out[144]:
0 1 2 3 4 5 6 7 8
0 0 0 0 1 0 0 0 0 0
1 0 0 3 2 0 0 0 0 0

Why do I get:

ValueError: Must pass 2-d input

I think pd.DataFrame() tries to convert it to NDArray like as follows:

In [148]: np.array(list_arrays)
Out[148]:
array([[[0, 0, 0, 1, 0, 0, 0, 0, 0]],

[[0, 0, 3, 2, 0, 0, 0, 0, 0]]], dtype=uint8)

In [149]: np.array(list_arrays).shape
Out[149]: (2, 1, 9) # <----- NOTE: 3D array


Related Topics



Leave a reply



Submit