julia crea un dataframe vacío y anexa filas a él


Estoy probando el módulo Julia DataFrames. Estoy interesado en él, así que puedo usarlo para trazar simulaciones simples en Tábano. Quiero poder agregar filas iterativamente al dataframe y quiero inicializarlo como vacío.

Los tutoriales/documentación sobre cómo hacer esto son escasos (la mayoría de la documentación describe cómo analizar los datos importados).

Añadir a un dataframe no vacío es sencillo:

df = DataFrame(A = [1, 2], B = [4, 5])
push!(df, [3 6])

Esto vuelve.

3x2 DataFrame
| Row | A | B |
|-----|---|---|
| 1   | 1 | 4 |
| 2   | 2 | 5 |
| 3   | 3 | 6 |

Pero para un init vacío I obtener errores.

df = DataFrame(A = [], B = [])
push!(df, [3, 6])

Mensaje de error:

ArgumentError("Error adding 3 to column :A. Possible type mis-match.")
while loading In[220], in expression starting on line 2

¿Cuál es la mejor manera de inicializar un DataFrame Julia vacío para que pueda agregar iterativamente elementos más tarde en un bucle for?

Author: bluesmoon, 2014-10-05

2 answers

Una matriz de longitud cero definida usando solo [] carecerá de suficiente información de tipo.

julia> typeof([])
Array{None,1}

Así que para evitar ese problema es simplemente indicar el tipo.

julia> typeof(Int64[])
Array{Int64,1}

Y puede aplicar eso a su problema de DataFrame

julia> df = DataFrame(A = Int64[], B = Int64[])
0x2 DataFrame

julia> push!(df, [3  6])

julia> df
1x2 DataFrame
| Row | A | B |
|-----|---|---|
| 1   | 3 | 6 |
 27
Author: waTeim,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2014-10-05 08:59:32
using Pkg, CSV, DataFrames

iris = CSV.read(joinpath(Pkg.dir("DataFrames"), "test/data/iris.csv"))

new_iris = similar(iris, nrow(iris))

head(new_iris, 2)
# 2×5 DataFrame
# │ Row │ SepalLength │ SepalWidth │ PetalLength │ PetalWidth │ Species │
# ├─────┼─────────────┼────────────┼─────────────┼────────────┼─────────┤
# │ 1   │ missing     │ missing    │ missing     │ missing    │ missing │
# │ 2   │ missing     │ missing    │ missing     │ missing    │ missing │

for (i, row) in enumerate(eachrow(iris))
    new_iris[i, :] = row[:]
end

head(new_iris, 2)

# 2×5 DataFrame
# │ Row │ SepalLength │ SepalWidth │ PetalLength │ PetalWidth │ Species │
# ├─────┼─────────────┼────────────┼─────────────┼────────────┼─────────┤
# │ 1   │ 5.1         │ 3.5        │ 1.4         │ 0.2        │ setosa  │
# │ 2   │ 4.9         │ 3.0        │ 1.4         │ 0.2        │ setosa  │
 0
Author: The Unfun Cat,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-09-24 19:48:08