|
| 1 | +import DataFrames.DataFrame |
| 2 | + |
| 3 | +""" |
| 4 | + DataFrame(gr::T; type = :node) where T <:AbstractMetaGraph |
| 5 | +
|
| 6 | +Construct a DataFrame from a MetaGraph from either its node or edge properties. |
| 7 | +
|
| 8 | +`gr` is a MetaGraph. |
| 9 | +
|
| 10 | +Optional keyword arguments: |
| 11 | +
|
| 12 | +`type` is a Symbol valued either :node or :edge such that the DataFrame is populated with node or edge |
| 13 | +properties stored in `gr`. Default is :node. |
| 14 | +
|
| 15 | +""" |
| 16 | +function DataFrame(gr::T; type = :node) where T <:AbstractMetaGraph |
| 17 | + fl, prps, en, nu = if type == :node |
| 18 | + :node => Int[], gr.vprops, vertices, nv |
| 19 | + elseif type == :edge |
| 20 | + :edge => Edge[], gr.eprops, edges, ne |
| 21 | + else |
| 22 | + error("specify type equal to :node or :edge") |
| 23 | + end |
| 24 | + |
| 25 | + dx = DataFrame(fl) |
| 26 | + |
| 27 | + x = unique(reduce(vcat, values(prps))) |
| 28 | + for y in x |
| 29 | + for (k, v) in y |
| 30 | + dx[!, k] = typeof(v)[] # may be a problem if type is not consistent in y? |
| 31 | + allowmissing!(dx, k) |
| 32 | + end |
| 33 | + end |
| 34 | + |
| 35 | + dx = similar(dx, nu(gr)) |
| 36 | + |
| 37 | + for (i, e) in (enumerate∘en)(gr) |
| 38 | + dx[i, type] = e |
| 39 | + pr = props(gr, e) |
| 40 | + for (nme, val) in pr |
| 41 | + dx[i, nme] = val |
| 42 | + end |
| 43 | + end |
| 44 | + |
| 45 | + # remove missing when possible |
| 46 | + for v in Symbol.(names(dx)) |
| 47 | + if !any(ismissing.(dx[!, v])) |
| 48 | + disallowmissing!(dx, v) |
| 49 | + end |
| 50 | + end |
| 51 | + return dx |
| 52 | +end |
0 commit comments