Skip to content

Commit c391085

Browse files
authored
Merge pull request #23 from emfeltham/master
Construct DataFrame from MetaGraph?
2 parents dbb5880 + b5c4605 commit c391085

File tree

2 files changed

+54
-0
lines changed

2 files changed

+54
-0
lines changed

src/DataFrame.jl

Lines changed: 52 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,52 @@
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 (enumerateen)(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

src/GraphDataFrameBridge.jl

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,8 @@ export MetaGraph, MetaDiGraph
77
import MetaGraphs.MetaGraph
88
import MetaGraphs.MetaDiGraph
99

10+
include("DataFrame.jl")
11+
export DataFrame
1012

1113
function MetaGraph(
1214
df::T,

0 commit comments

Comments
 (0)