Repository: networkx/networkx

Issue:
Invalid call to from_pandas_dataframe function?
While looking for a problem in my branch, I noticed what looks like an invalid chunk of code (direct link to the line [here](https://github.com/networkx/networkx/blob/d7d906e1d16ef331da0bc1d149953e7532155acc/networkx/convert.py#L133-L134)):

```
    try:
        import pandas as pd
        if isinstance(data, pd.DataFrame):
            try:
                return nx.from_pandas_dataframe(data, create_using=create_using)
            except:
                msg = "Input is not a correct Pandas DataFrame."
                raise nx.NetworkXError(msg)
```

`from_pandas_dataframe` requires, at the very least, _three_ arguments -- with `create_from` being an optional keyword argument. Because the `try: except:` block is untyped, this will always report a `NetworkXError` no matter what.

Invalid call to from_pandas_dataframe function?
While looking for a problem in my branch, I noticed what looks like an invalid chunk of code (direct link to the line [here](https://github.com/networkx/networkx/blob/d7d906e1d16ef331da0bc1d149953e7532155acc/networkx/convert.py#L133-L134)):

```
    try:
        import pandas as pd
        if isinstance(data, pd.DataFrame):
            try:
                return nx.from_pandas_dataframe(data, create_using=create_using)
            except:
                msg = "Input is not a correct Pandas DataFrame."
                raise nx.NetworkXError(msg)
```

`from_pandas_dataframe` requires, at the very least, _three_ arguments -- with `create_from` being an optional keyword argument. Because the `try: except:` block is untyped, this will always report a `NetworkXError` no matter what.



Discussion:
I agree, that isn't going to work.  I guess we are not testing this and we should.  

I agree, that isn't going to work.  I guess we are not testing this and we should.  


Resolving patch:
diff --git a/networkx/convert.py b/networkx/convert.py
--- a/networkx/convert.py
+++ b/networkx/convert.py
@@ -24,13 +24,14 @@
 import warnings
 import networkx as nx
 __author__ = """\n""".join(['Aric Hagberg <aric.hagberg@gmail.com>',
-                           'Pieter Swart (swart@lanl.gov)',
-                           'Dan Schult(dschult@colgate.edu)'])
+                            'Pieter Swart (swart@lanl.gov)',
+                            'Dan Schult(dschult@colgate.edu)'])
 __all__ = ['to_networkx_graph',
            'from_dict_of_dicts', 'to_dict_of_dicts',
            'from_dict_of_lists', 'to_dict_of_lists',
            'from_edgelist', 'to_edgelist']
 
+
 def _prep_create_using(create_using):
     """Return a graph object ready to be populated.
 
@@ -47,7 +48,8 @@ def _prep_create_using(create_using):
         raise TypeError("Input graph is not a networkx graph type")
     return create_using
 
-def to_networkx_graph(data,create_using=None,multigraph_input=False):
+
+def to_networkx_graph(data, create_using=None, multigraph_input=False):
     """Make a NetworkX graph from a known data structure.
 
     The preferred way to call this is automatically
@@ -67,8 +69,9 @@ def to_networkx_graph(data,create_using=None,multigraph_input=False):
        Current known types are:
          any NetworkX graph
          dict-of-dicts
-         dist-of-lists
+         dict-of-lists
          list of edges
+         Pandas DataFrame (row per edge)
          numpy matrix
          numpy ndarray
          scipy sparse matrix
@@ -85,45 +88,45 @@ def to_networkx_graph(data,create_using=None,multigraph_input=False):
 
     """
     # NX graph
-    if hasattr(data,"adj"):
+    if hasattr(data, "adj"):
         try:
-            result= from_dict_of_dicts(data.adj,\
-                    create_using=create_using,\
-                    multigraph_input=data.is_multigraph())
-            if hasattr(data,'graph'): # data.graph should be dict-like
+            result = from_dict_of_dicts(data.adj,
+                                        create_using=create_using,
+                                        multigraph_input=data.is_multigraph())
+            if hasattr(data, 'graph'):  # data.graph should be dict-like
                 result.graph.update(data.graph)
-            if hasattr(data,'node'): # data.node should be dict-like
-                result._node.update( (n,dd.copy()) for n,dd in data.node.items() )
+            if hasattr(data, 'node'):  # data.node should be dict-like
+                result._node.update((n, dd.copy()) for n, dd in data.node.items())
             return result
         except:
             raise nx.NetworkXError("Input is not a correct NetworkX graph.")
 
     # pygraphviz  agraph
-    if hasattr(data,"is_strict"):
+    if hasattr(data, "is_strict"):
         try:
-            return nx.nx_agraph.from_agraph(data,create_using=create_using)
+            return nx.nx_agraph.from_agraph(data, create_using=create_using)
         except:
             raise nx.NetworkXError("Input is not a correct pygraphviz graph.")
 
     # dict of dicts/lists
-    if isinstance(data,dict):
+    if isinstance(data, dict):
         try:
-            return from_dict_of_dicts(data,create_using=create_using,\
-                    multigraph_input=multigraph_input)
+            return from_dict_of_dicts(data, create_using=create_using,
+                                      multigraph_input=multigraph_input)
         except:
             try:
-                return from_dict_of_lists(data,create_using=create_using)
+                return from_dict_of_lists(data, create_using=create_using)
             except:
                 raise TypeError("Input is not known type.")
 
     # list or generator of edges
-    if (isinstance(data, list)
-        or isinstance(data, tuple)
-        or hasattr(data, '_adjdict')
-        or hasattr(data, 'next')
-        or hasattr(data, '__next__')):
+    if (isinstance(data, list) or
+        isinstance(data, tuple) or
+        hasattr(data, '_adjdict') or
+        hasattr(data, 'next') or
+        hasattr(data, '__next__')):
         try:
-            return from_edgelist(data,create_using=create_using)
+            return from_edgelist(data, create_using=create_using)
         except:
             raise nx.NetworkXError("Input is not a valid edge list")
 
@@ -132,7 +135,7 @@ def to_networkx_graph(data,create_using=None,multigraph_input=False):
         import pandas as pd
         if isinstance(data, pd.DataFrame):
             try:
-                return nx.from_pandas_dataframe(data, create_using=create_using)
+                return nx.from_pandas_dataframe(data, edge_attr=True, create_using=create_using)
             except:
                 msg = "Input is not a correct Pandas DataFrame."
                 raise nx.NetworkXError(msg)
@@ -143,13 +146,12 @@ def to_networkx_graph(data,create_using=None,multigraph_input=False):
     # numpy matrix or ndarray
     try:
         import numpy
-        if isinstance(data,numpy.matrix) or \
-               isinstance(data,numpy.ndarray):
+        if isinstance(data, numpy.matrix) or isinstance(data, numpy.ndarray):
             try:
-                return nx.from_numpy_matrix(data,create_using=create_using)
+                return nx.from_numpy_matrix(data, create_using=create_using)
             except:
-                raise nx.NetworkXError(\
-                  "Input is not a correct numpy matrix or array.")
+                raise nx.NetworkXError(
+                    "Input is not a correct numpy matrix or array.")
     except ImportError:
         warnings.warn('numpy not found, skipping conversion test.',
                       ImportWarning)
@@ -157,24 +159,23 @@ def to_networkx_graph(data,create_using=None,multigraph_input=False):
     # scipy sparse matrix - any format
     try:
         import scipy
-        if hasattr(data,"format"):
+        if hasattr(data, "format"):
             try:
-                return nx.from_scipy_sparse_matrix(data,create_using=create_using)
+                return nx.from_scipy_sparse_matrix(data, create_using=create_using)
             except:
-                raise nx.NetworkXError(\
-                      "Input is not a correct scipy sparse matrix type.")
+                raise nx.NetworkXError(
+                    "Input is not a correct scipy sparse matrix type.")
     except ImportError:
         warnings.warn('scipy not found, skipping conversion test.',
                       ImportWarning)
 
-
-    raise nx.NetworkXError(\
-          "Input is not a known data type for conversion.")
+    raise nx.NetworkXError(
+        "Input is not a known data type for conversion.")
 
     return
 
 
-def to_dict_of_lists(G,nodelist=None):
+def to_dict_of_lists(G, nodelist=None):
     """Return adjacency representation of graph as a dictionary of lists.
 
     Parameters
@@ -191,14 +192,15 @@ def to_dict_of_lists(G,nodelist=None):
 
     """
     if nodelist is None:
-        nodelist=G
+        nodelist = G
 
     d = {}
     for n in nodelist:
-        d[n]=[nbr for nbr in G.neighbors(n) if nbr in nodelist]
+        d[n] = [nbr for nbr in G.neighbors(n) if nbr in nodelist]
     return d
 
-def from_dict_of_lists(d,create_using=None):
+
+def from_dict_of_lists(d, create_using=None):
     """Return a graph from a dictionary of lists.
 
     Parameters
@@ -218,25 +220,25 @@ def from_dict_of_lists(d,create_using=None):
     >>> G=nx.Graph(dol) # use Graph constructor
 
     """
-    G=_prep_create_using(create_using)
+    G = _prep_create_using(create_using)
     G.add_nodes_from(d)
     if G.is_multigraph() and not G.is_directed():
         # a dict_of_lists can't show multiedges.  BUT for undirected graphs,
         # each edge shows up twice in the dict_of_lists.
         # So we need to treat this case separately.
-        seen={}
-        for node,nbrlist in d.items():
+        seen = {}
+        for node, nbrlist in d.items():
             for nbr in nbrlist:
                 if nbr not in seen:
-                    G.add_edge(node,nbr)
-            seen[node]=1  # don't allow reverse edge to show up
+                    G.add_edge(node, nbr)
+            seen[node] = 1  # don't allow reverse edge to show up
     else:
-        G.add_edges_from( ((node,nbr) for node,nbrlist in d.items()
-                           for nbr in nbrlist) )
+        G.add_edges_from(((node, nbr) for node, nbrlist in d.items()
+                          for nbr in nbrlist))
     return G
 
 
-def to_dict_of_dicts(G,nodelist=None,edge_data=None):
+def to_dict_of_dicts(G, nodelist=None, edge_data=None):
     """Return adjacency representation of graph as a dictionary of dictionaries.
 
     Parameters
@@ -254,28 +256,29 @@ def to_dict_of_dicts(G,nodelist=None,edge_data=None):
        If edgedata is None, the edgedata in G is used to fill the values.
        If G is a multigraph, the edgedata is a dict for each pair (u,v).
     """
-    dod={}
+    dod = {}
     if nodelist is None:
         if edge_data is None:
-            for u,nbrdict in G.adjacency():
-                dod[u]=nbrdict.copy()
-        else: # edge_data is not None
-            for u,nbrdict in G.adjacency():
-                dod[u]=dod.fromkeys(nbrdict, edge_data)
-    else: # nodelist is not None
+            for u, nbrdict in G.adjacency():
+                dod[u] = nbrdict.copy()
+        else:  # edge_data is not None
+            for u, nbrdict in G.adjacency():
+                dod[u] = dod.fromkeys(nbrdict, edge_data)
+    else:  # nodelist is not None
         if edge_data is None:
             for u in nodelist:
-                dod[u]={}
-                for v,data in ((v,data) for v,data in G[u].items() if v in nodelist):
-                    dod[u][v]=data
-        else: # nodelist and edge_data are not None
+                dod[u] = {}
+                for v, data in ((v, data) for v, data in G[u].items() if v in nodelist):
+                    dod[u][v] = data
+        else:  # nodelist and edge_data are not None
             for u in nodelist:
-                dod[u]={}
-                for v in ( v for v in G[u] if v in nodelist):
-                    dod[u][v]=edge_data
+                dod[u] = {}
+                for v in (v for v in G[u] if v in nodelist):
+                    dod[u][v] = edge_data
     return dod
 
-def from_dict_of_dicts(d,create_using=None,multigraph_input=False):
+
+def from_dict_of_dicts(d, create_using=None, multigraph_input=False):
     """Return a graph from a dictionary of dictionaries.
 
     Parameters
@@ -300,62 +303,63 @@ def from_dict_of_dicts(d,create_using=None,multigraph_input=False):
     >>> G=nx.Graph(dod) # use Graph constructor
 
     """
-    G=_prep_create_using(create_using)
+    G = _prep_create_using(create_using)
     G.add_nodes_from(d)
     # is dict a MultiGraph or MultiDiGraph?
     if multigraph_input:
         # make a copy of the list of edge data (but not the edge data)
         if G.is_directed():
             if G.is_multigraph():
-                G.add_edges_from( (u,v,key,data)
-                                  for u,nbrs in d.items()
-                                  for v,datadict in nbrs.items()
-                                  for key,data in datadict.items()
-                                )
+                G.add_edges_from((u, v, key, data)
+                                 for u, nbrs in d.items()
+                                 for v, datadict in nbrs.items()
+                                 for key, data in datadict.items()
+                                 )
             else:
-                G.add_edges_from( (u,v,data)
-                                  for u,nbrs in d.items()
-                                  for v,datadict in nbrs.items()
-                                  for key,data in datadict.items()
-                                )
-        else: # Undirected
+                G.add_edges_from((u, v, data)
+                                 for u, nbrs in d.items()
+                                 for v, datadict in nbrs.items()
+                                 for key, data in datadict.items()
+                                 )
+        else:  # Undirected
             if G.is_multigraph():
-                seen=set()   # don't add both directions of undirected graph
-                for u,nbrs in d.items():
-                    for v,datadict in nbrs.items():
-                        if (u,v) not in seen:
-                            G.add_edges_from( (u,v,key,data)
-                                               for key,data in datadict.items()
-                                              )
-                            seen.add((v,u))
+                seen = set()   # don't add both directions of undirected graph
+                for u, nbrs in d.items():
+                    for v, datadict in nbrs.items():
+                        if (u, v) not in seen:
+                            G.add_edges_from((u, v, key, data)
+                                             for key, data in datadict.items()
+                                             )
+                            seen.add((v, u))
             else:
-                seen=set()   # don't add both directions of undirected graph
-                for u,nbrs in d.items():
-                    for v,datadict in nbrs.items():
-                        if (u,v) not in seen:
-                            G.add_edges_from( (u,v,data)
-                                        for key,data in datadict.items() )
-                            seen.add((v,u))
-
-    else: # not a multigraph to multigraph transfer
+                seen = set()   # don't add both directions of undirected graph
+                for u, nbrs in d.items():
+                    for v, datadict in nbrs.items():
+                        if (u, v) not in seen:
+                            G.add_edges_from((u, v, data)
+                                             for key, data in datadict.items())
+                            seen.add((v, u))
+
+    else:  # not a multigraph to multigraph transfer
         if G.is_multigraph() and not G.is_directed():
             # d can have both representations u-v, v-u in dict.  Only add one.
             # We don't need this check for digraphs since we add both directions,
             # or for Graph() since it is done implicitly (parallel edges not allowed)
-            seen=set()
-            for u,nbrs in d.items():
-                for v,data in nbrs.items():
-                    if (u,v) not in seen:
-                        G.add_edge(u,v,key=0)
+            seen = set()
+            for u, nbrs in d.items():
+                for v, data in nbrs.items():
+                    if (u, v) not in seen:
+                        G.add_edge(u, v, key=0)
                         G[u][v][0].update(data)
-                    seen.add((v,u))
+                    seen.add((v, u))
         else:
-            G.add_edges_from( ( (u,v,data)
-                                for u,nbrs in d.items()
-                                for v,data in nbrs.items()) )
+            G.add_edges_from(((u, v, data)
+                              for u, nbrs in d.items()
+                              for v, data in nbrs.items()))
     return G
 
-def to_edgelist(G,nodelist=None):
+
+def to_edgelist(G, nodelist=None):
     """Return a list of edges in the graph.
 
     Parameters
@@ -370,9 +374,10 @@ def to_edgelist(G,nodelist=None):
     if nodelist is None:
         return G.edges(data=True)
     else:
-        return G.edges(nodelist,data=True)
+        return G.edges(nodelist, data=True)
+
 
-def from_edgelist(edgelist,create_using=None):
+def from_edgelist(edgelist, create_using=None):
     """Return a graph from a list of edges.
 
     Parameters
@@ -392,6 +397,6 @@ def from_edgelist(edgelist,create_using=None):
     >>> G=nx.Graph(edgelist) # use Graph constructor
 
     """
-    G=_prep_create_using(create_using)
+    G = _prep_create_using(create_using)
     G.add_edges_from(edgelist)
     return G
diff --git a/networkx/convert_matrix.py b/networkx/convert_matrix.py
--- a/networkx/convert_matrix.py
+++ b/networkx/convert_matrix.py
@@ -32,13 +32,14 @@
 from networkx.convert import _prep_create_using
 from networkx.utils import not_implemented_for
 __author__ = """\n""".join(['Aric Hagberg <aric.hagberg@gmail.com>',
-                           'Pieter Swart (swart@lanl.gov)',
-                           'Dan Schult(dschult@colgate.edu)'])
+                            'Pieter Swart (swart@lanl.gov)',
+                            'Dan Schult(dschult@colgate.edu)'])
 __all__ = ['from_numpy_matrix', 'to_numpy_matrix',
            'from_pandas_dataframe', 'to_pandas_dataframe',
            'to_numpy_recarray',
            'from_scipy_sparse_matrix', 'to_scipy_sparse_matrix']
 
+
 def to_pandas_dataframe(G, nodelist=None, dtype=None, order=None,
                         multigraph_weight=sum, weight='weight', nonedge=0.0):
     """Return the graph adjacency matrix as a Pandas DataFrame.
@@ -127,9 +128,9 @@ def to_pandas_dataframe(G, nodelist=None, dtype=None, order=None,
     return pd.DataFrame(data=M, index=nodelist, columns=nodelist)
 
 
-def from_pandas_dataframe(df, source, target, edge_attr=None,
-        create_using=None):
-    """Return a graph from Pandas DataFrame.
+def from_pandas_dataframe(df, source='source', target='target', edge_attr=None,
+                          create_using=None):
+    """Return a graph from Pandas DataFrame containing an edge list.
 
     The Pandas DataFrame should contain at least two columns of node names and
     zero or more columns of node attributes. Each row will be processed as one
@@ -189,6 +190,13 @@ def from_pandas_dataframe(df, source, target, edge_attr=None,
     10
     >>> G['E']['C']['cost']
     9
+    >>> edges = pd.DataFrame({'source': [0, 1, 2],
+    ...                       'target': [2, 2, 3],
+    ...                       'weight': [3, 4, 5],
+    ...                       'color': ['red', 'blue', 'blue']})
+    >>> G = nx.from_pandas_dataframe(edges, edge_attr=True)
+    >>> G[0][2]['color']
+    'red'
     """
 
     g = _prep_create_using(create_using)
@@ -210,7 +218,7 @@ def from_pandas_dataframe(df, source, target, edge_attr=None,
             edge_i = [(i, df.columns.get_loc(i)) for i in edge_attr]
         # If a string or int is passed
         else:
-            edge_i = [(edge_attr, df.columns.get_loc(edge_attr)),]
+            edge_i = [(edge_attr, df.columns.get_loc(edge_attr)), ]
 
         # Iteration on values returns the rows as Numpy arrays
         for row in df.values:
@@ -230,6 +238,7 @@ def from_pandas_dataframe(df, source, target, edge_attr=None,
 
     return g
 
+
 def to_numpy_matrix(G, nodelist=None, dtype=None, order=None,
                     multigraph_weight=sum, weight='weight', nonedge=0.0):
     """Return the graph adjacency matrix as a NumPy matrix.
@@ -328,9 +337,9 @@ def to_numpy_matrix(G, nodelist=None, dtype=None, order=None,
         msg = "Ambiguous ordering: `nodelist` contained duplicates."
         raise nx.NetworkXError(msg)
 
-    nlen=len(nodelist)
+    nlen = len(nodelist)
     undirected = not G.is_directed()
-    index=dict(zip(nodelist,range(nlen)))
+    index = dict(zip(nodelist, range(nlen)))
 
     # Initially, we start with an array of nans.  Then we populate the matrix
     # using data from the graph.  Afterwards, any leftover nans will be
@@ -368,26 +377,26 @@ def to_numpy_matrix(G, nodelist=None, dtype=None, order=None,
         # Handle MultiGraphs and MultiDiGraphs
         M = np.full((nlen, nlen), np.nan, order=order)
         # use numpy nan-aware operations
-        operator={sum:np.nansum, min:np.nanmin, max:np.nanmax}
+        operator = {sum: np.nansum, min: np.nanmin, max: np.nanmax}
         try:
-            op=operator[multigraph_weight]
+            op = operator[multigraph_weight]
         except:
             raise ValueError('multigraph_weight must be sum, min, or max')
 
-        for u,v,attrs in G.edges(data=True):
+        for u, v, attrs in G.edges(data=True):
             if (u in nodeset) and (v in nodeset):
                 i, j = index[u], index[v]
                 e_weight = attrs.get(weight, 1)
-                M[i,j] = op([e_weight, M[i,j]])
+                M[i, j] = op([e_weight, M[i, j]])
                 if undirected:
-                    M[j,i] = M[i,j]
+                    M[j, i] = M[i, j]
     else:
         # Graph or DiGraph, this is much faster than above
         M = np.full((nlen, nlen), np.nan, order=order)
-        for u,nbrdict in G.adjacency():
-            for v,d in nbrdict.items():
+        for u, nbrdict in G.adjacency():
+            for v, d in nbrdict.items():
                 try:
-                    M[index[u],index[v]] = d.get(weight,1)
+                    M[index[u], index[v]] = d.get(weight, 1)
                 except KeyError:
                     # This occurs when there are fewer desired nodes than
                     # there are nodes in the graph: len(nodelist) < len(G)
@@ -485,28 +494,28 @@ def from_numpy_matrix(A, parallel_edges=False, create_using=None):
     """
     # This should never fail if you have created a numpy matrix with numpy...
     import numpy as np
-    kind_to_python_type={'f':float,
-                         'i':int,
-                         'u':int,
-                         'b':bool,
-                         'c':complex,
-                         'S':str,
-                         'V':'void'}
-    try: # Python 3.x
-        blurb = chr(1245) # just to trigger the exception
-        kind_to_python_type['U']=str
-    except ValueError: # Python 2.6+
-        kind_to_python_type['U']=unicode
-    G=_prep_create_using(create_using)
-    n,m=A.shape
-    if n!=m:
+    kind_to_python_type = {'f': float,
+                           'i': int,
+                           'u': int,
+                           'b': bool,
+                           'c': complex,
+                           'S': str,
+                           'V': 'void'}
+    try:  # Python 3.x
+        blurb = chr(1245)  # just to trigger the exception
+        kind_to_python_type['U'] = str
+    except ValueError:  # Python 2.6+
+        kind_to_python_type['U'] = unicode
+    G = _prep_create_using(create_using)
+    n, m = A.shape
+    if n != m:
         raise nx.NetworkXError("Adjacency matrix is not square.",
-                               "nx,ny=%s"%(A.shape,))
-    dt=A.dtype
+                               "nx,ny=%s" % (A.shape,))
+    dt = A.dtype
     try:
-        python_type=kind_to_python_type[dt.kind]
+        python_type = kind_to_python_type[dt.kind]
     except:
-        raise TypeError("Unknown numpy data type: %s"%dt)
+        raise TypeError("Unknown numpy data type: %s" % dt)
 
     # Make sure we get even the isolated nodes of the graph.
     G.add_nodes_from(range(n))
@@ -607,19 +616,19 @@ def to_numpy_recarray(G, nodelist=None, dtype=None, order=None):
     if len(nodelist) != len(nodeset):
         msg = "Ambiguous ordering: `nodelist` contained duplicates."
         raise nx.NetworkXError(msg)
-    nlen=len(nodelist)
+    nlen = len(nodelist)
     undirected = not G.is_directed()
-    index=dict(zip(nodelist,range(nlen)))
-    M = np.zeros((nlen,nlen), dtype=dtype, order=order)
+    index = dict(zip(nodelist, range(nlen)))
+    M = np.zeros((nlen, nlen), dtype=dtype, order=order)
 
-    names=M.dtype.names
-    for u,v,attrs in G.edges(data=True):
+    names = M.dtype.names
+    for u, v, attrs in G.edges(data=True):
         if (u in nodeset) and (v in nodeset):
-            i,j = index[u],index[v]
-            values=tuple([attrs[n] for n in names])
-            M[i,j] = values
+            i, j = index[u], index[v]
+            values = tuple([attrs[n] for n in names])
+            M[i, j] = values
             if undirected:
-                M[j,i] = M[i,j]
+                M[j, i] = M[i, j]
 
     return M.view(np.recarray)
 
@@ -717,19 +726,19 @@ def to_scipy_sparse_matrix(G, nodelist=None, dtype=None,
         msg = "Ambiguous ordering: `nodelist` contained duplicates."
         raise nx.NetworkXError(msg)
 
-    index = dict(zip(nodelist,range(nlen)))
-    coefficients = zip(*((index[u],index[v],d.get(weight,1))
-                         for u,v,d in G.edges(nodelist, data=True)
+    index = dict(zip(nodelist, range(nlen)))
+    coefficients = zip(*((index[u], index[v], d.get(weight, 1))
+                         for u, v, d in G.edges(nodelist, data=True)
                          if u in index and v in index))
     try:
-        row,col,data = coefficients
+        row, col, data = coefficients
     except ValueError:
         # there is no edge in the subgraph
-        row,col,data = [],[],[]
+        row, col, data = [], [], []
 
     if G.is_directed():
-        M = sparse.coo_matrix((data,(row,col)),
-                              shape=(nlen,nlen), dtype=dtype)
+        M = sparse.coo_matrix((data, (row, col)),
+                              shape=(nlen, nlen), dtype=dtype)
     else:
         # symmetrize matrix
         d = data + data
@@ -739,17 +748,17 @@ def to_scipy_sparse_matrix(G, nodelist=None, dtype=None,
         # so we subtract the data on the diagonal
         selfloops = list(G.selfloop_edges(data=True))
         if selfloops:
-            diag_index,diag_data = zip(*((index[u],-d.get(weight,1))
-                                         for u,v,d in selfloops
-                                         if u in index and v in index))
+            diag_index, diag_data = zip(*((index[u], -d.get(weight, 1))
+                                          for u, v, d in selfloops
+                                          if u in index and v in index))
             d += diag_data
             r += diag_index
             c += diag_index
-        M = sparse.coo_matrix((d, (r, c)), shape=(nlen,nlen), dtype=dtype)
+        M = sparse.coo_matrix((d, (r, c)), shape=(nlen, nlen), dtype=dtype)
     try:
         return M.asformat(format)
     except AttributeError:
-        raise nx.NetworkXError("Unknown sparse matrix format: %s"%format)
+        raise nx.NetworkXError("Unknown sparse matrix format: %s" % format)
 
 
 def _csr_gen_triples(A):
@@ -760,7 +769,7 @@ def _csr_gen_triples(A):
     nrows = A.shape[0]
     data, indices, indptr = A.data, A.indices, A.indptr
     for i in range(nrows):
-        for j in range(indptr[i], indptr[i+1]):
+        for j in range(indptr[i], indptr[i + 1]):
             yield i, indices[j], data[j]
 
 
@@ -772,7 +781,7 @@ def _csc_gen_triples(A):
     ncols = A.shape[1]
     data, indices, indptr = A.data, A.indices, A.indptr
     for i in range(ncols):
-        for j in range(indptr[i], indptr[i+1]):
+        for j in range(indptr[i], indptr[i + 1]):
             yield indices[j], i, data[j]
 
 
@@ -877,10 +886,10 @@ def from_scipy_sparse_matrix(A, parallel_edges=False, create_using=None,
 
     """
     G = _prep_create_using(create_using)
-    n,m = A.shape
+    n, m = A.shape
     if n != m:
-        raise nx.NetworkXError(\
-              "Adjacency matrix is not square. nx,ny=%s"%(A.shape,))
+        raise nx.NetworkXError(
+            "Adjacency matrix is not square. nx,ny=%s" % (A.shape,))
     # Make sure we get even the isolated nodes of the graph.
     G.add_nodes_from(range(n))
     # Create an iterable over (u, v, w) triples and for each triple, add an


Test patch:
diff --git a/networkx/tests/test_convert.py b/networkx/tests/test_convert.py
--- a/networkx/tests/test_convert.py
+++ b/networkx/tests/test_convert.py
@@ -1,198 +1,202 @@
 #!/usr/bin/env python
-from nose.tools import *
-from networkx.testing import *
-from networkx import *
-from networkx.convert import *
-from networkx.algorithms.operators import *
-from networkx.generators.classic import barbell_graph,cycle_graph
+from nose.tools import assert_equal, assert_not_equal, assert_true, assert_false
+
+import networkx as nx
+from networkx.testing import assert_nodes_equal, assert_edges_equal, assert_graphs_equal
+from networkx.convert import (to_networkx_graph,
+                              to_dict_of_dicts,
+                              from_dict_of_dicts,
+                              to_dict_of_lists,
+                              from_dict_of_lists)
+from networkx.generators.classic import barbell_graph, cycle_graph
+
 
 class TestConvert():
-    def edgelists_equal(self,e1,e2):
-        return sorted(sorted(e) for e in e1)==sorted(sorted(e) for e in e2)
+    def edgelists_equal(self, e1, e2):
+        return sorted(sorted(e) for e in e1) == sorted(sorted(e) for e in e2)
 
     def test_simple_graphs(self):
         for dest, source in [(to_dict_of_dicts, from_dict_of_dicts),
                              (to_dict_of_lists, from_dict_of_lists)]:
-            G=barbell_graph(10,3)
-            G.graph={}
-            dod=dest(G)
+            G = barbell_graph(10, 3)
+            G.graph = {}
+            dod = dest(G)
 
             # Dict of [dicts, lists]
-            GG=source(dod)
-            assert_graphs_equal(G,GG)
-            GW=to_networkx_graph(dod)
-            assert_graphs_equal(G,GW)
-            GI=Graph(dod)
-            assert_graphs_equal(G,GI)
+            GG = source(dod)
+            assert_graphs_equal(G, GG)
+            GW = to_networkx_graph(dod)
+            assert_graphs_equal(G, GW)
+            GI = nx.Graph(dod)
+            assert_graphs_equal(G, GI)
 
             # With nodelist keyword
-            P4=path_graph(4)
-            P3=path_graph(3)
-            P4.graph={}
-            P3.graph={}
-            dod=dest(P4,nodelist=[0,1,2])
-            Gdod=Graph(dod)
-            assert_graphs_equal(Gdod,P3)
+            P4 = nx.path_graph(4)
+            P3 = nx.path_graph(3)
+            P4.graph = {}
+            P3.graph = {}
+            dod = dest(P4, nodelist=[0, 1, 2])
+            Gdod = nx.Graph(dod)
+            assert_graphs_equal(Gdod, P3)
 
     def test_digraphs(self):
         for dest, source in [(to_dict_of_dicts, from_dict_of_dicts),
                              (to_dict_of_lists, from_dict_of_lists)]:
-            G=cycle_graph(10)
+            G = cycle_graph(10)
 
             # Dict of [dicts, lists]
-            dod=dest(G)
-            GG=source(dod)
+            dod = dest(G)
+            GG = source(dod)
             assert_nodes_equal(sorted(G.nodes()), sorted(GG.nodes()))
             assert_edges_equal(sorted(G.edges()), sorted(GG.edges()))
-            GW=to_networkx_graph(dod)
+            GW = to_networkx_graph(dod)
             assert_nodes_equal(sorted(G.nodes()), sorted(GW.nodes()))
             assert_edges_equal(sorted(G.edges()), sorted(GW.edges()))
-            GI=Graph(dod)
+            GI = nx.Graph(dod)
             assert_nodes_equal(sorted(G.nodes()), sorted(GI.nodes()))
             assert_edges_equal(sorted(G.edges()), sorted(GI.edges()))
 
-            G=cycle_graph(10,create_using=DiGraph())
-            dod=dest(G)
-            GG=source(dod, create_using=DiGraph())
+            G = cycle_graph(10, create_using=nx.DiGraph())
+            dod = dest(G)
+            GG = source(dod, create_using=nx.DiGraph())
             assert_equal(sorted(G.nodes()), sorted(GG.nodes()))
             assert_equal(sorted(G.edges()), sorted(GG.edges()))
-            GW=to_networkx_graph(dod, create_using=DiGraph())
+            GW = to_networkx_graph(dod, create_using=nx.DiGraph())
             assert_equal(sorted(G.nodes()), sorted(GW.nodes()))
             assert_equal(sorted(G.edges()), sorted(GW.edges()))
-            GI=DiGraph(dod)
+            GI = nx.DiGraph(dod)
             assert_equal(sorted(G.nodes()), sorted(GI.nodes()))
             assert_equal(sorted(G.edges()), sorted(GI.edges()))
 
     def test_graph(self):
-        g = cycle_graph(10)
-        G = Graph()
+        g = nx.cycle_graph(10)
+        G = nx.Graph()
         G.add_nodes_from(g)
-        G.add_weighted_edges_from((u, v, u) for u,v in g.edges())
+        G.add_weighted_edges_from((u, v, u) for u, v in g.edges())
 
         # Dict of dicts
-        dod=to_dict_of_dicts(G)
-        GG=from_dict_of_dicts(dod,create_using=Graph())
+        dod = to_dict_of_dicts(G)
+        GG = from_dict_of_dicts(dod, create_using=nx.Graph())
         assert_nodes_equal(sorted(G.nodes()), sorted(GG.nodes()))
         assert_edges_equal(sorted(G.edges()), sorted(GG.edges()))
-        GW=to_networkx_graph(dod,create_using=Graph())
+        GW = to_networkx_graph(dod, create_using=nx.Graph())
         assert_nodes_equal(sorted(G.nodes()), sorted(GW.nodes()))
         assert_edges_equal(sorted(G.edges()), sorted(GW.edges()))
-        GI=Graph(dod)
+        GI = nx.Graph(dod)
         assert_equal(sorted(G.nodes()), sorted(GI.nodes()))
         assert_equal(sorted(G.edges()), sorted(GI.edges()))
 
         # Dict of lists
-        dol=to_dict_of_lists(G)
-        GG=from_dict_of_lists(dol,create_using=Graph())
+        dol = to_dict_of_lists(G)
+        GG = from_dict_of_lists(dol, create_using=nx.Graph())
         # dict of lists throws away edge data so set it to none
-        enone=[(u,v,{}) for (u,v,d) in G.edges(data=True)]
+        enone = [(u, v, {}) for (u, v, d) in G.edges(data=True)]
         assert_nodes_equal(sorted(G.nodes()), sorted(GG.nodes()))
         assert_edges_equal(enone, sorted(GG.edges(data=True)))
-        GW=to_networkx_graph(dol,create_using=Graph())
+        GW = to_networkx_graph(dol, create_using=nx.Graph())
         assert_nodes_equal(sorted(G.nodes()), sorted(GW.nodes()))
         assert_edges_equal(enone, sorted(GW.edges(data=True)))
-        GI=Graph(dol)
+        GI = nx.Graph(dol)
         assert_nodes_equal(sorted(G.nodes()), sorted(GI.nodes()))
         assert_edges_equal(enone, sorted(GI.edges(data=True)))
 
-
     def test_with_multiedges_self_loops(self):
         G = cycle_graph(10)
-        XG = Graph()
+        XG = nx.Graph()
         XG.add_nodes_from(G)
-        XG.add_weighted_edges_from((u, v, u) for u,v in G.edges())
-        XGM=MultiGraph()
+        XG.add_weighted_edges_from((u, v, u) for u, v in G.edges())
+        XGM = nx.MultiGraph()
         XGM.add_nodes_from(G)
-        XGM.add_weighted_edges_from((u, v, u) for u,v in G.edges())
-        XGM.add_edge(0,1,weight=2) # multiedge
-        XGS = Graph()
+        XGM.add_weighted_edges_from((u, v, u) for u, v in G.edges())
+        XGM.add_edge(0, 1, weight=2)  # multiedge
+        XGS = nx.Graph()
         XGS.add_nodes_from(G)
-        XGS.add_weighted_edges_from((u, v, u) for u,v in G.edges())
-        XGS.add_edge(0,0,weight=100) # self loop
+        XGS.add_weighted_edges_from((u, v, u) for u, v in G.edges())
+        XGS.add_edge(0, 0, weight=100)  # self loop
 
         # Dict of dicts
         # with self loops, OK
-        dod=to_dict_of_dicts(XGS)
-        GG=from_dict_of_dicts(dod,create_using=Graph())
+        dod = to_dict_of_dicts(XGS)
+        GG = from_dict_of_dicts(dod, create_using=nx.Graph())
         assert_nodes_equal(XGS.nodes(), GG.nodes())
         assert_edges_equal(XGS.edges(), GG.edges())
-        GW=to_networkx_graph(dod,create_using=Graph())
+        GW = to_networkx_graph(dod, create_using=nx.Graph())
         assert_nodes_equal(XGS.nodes(), GW.nodes())
         assert_edges_equal(XGS.edges(), GW.edges())
-        GI=Graph(dod)
+        GI = nx.Graph(dod)
         assert_nodes_equal(XGS.nodes(), GI.nodes())
         assert_edges_equal(XGS.edges(), GI.edges())
 
         # Dict of lists
         # with self loops, OK
-        dol=to_dict_of_lists(XGS)
-        GG=from_dict_of_lists(dol,create_using=Graph())
+        dol = to_dict_of_lists(XGS)
+        GG = from_dict_of_lists(dol, create_using=nx.Graph())
         # dict of lists throws away edge data so set it to none
-        enone=[(u,v,{}) for (u,v,d) in XGS.edges(data=True)]
+        enone = [(u, v, {}) for (u, v, d) in XGS.edges(data=True)]
         assert_nodes_equal(sorted(XGS.nodes()), sorted(GG.nodes()))
         assert_edges_equal(enone, sorted(GG.edges(data=True)))
-        GW=to_networkx_graph(dol,create_using=Graph())
+        GW = to_networkx_graph(dol, create_using=nx.Graph())
         assert_nodes_equal(sorted(XGS.nodes()), sorted(GW.nodes()))
         assert_edges_equal(enone, sorted(GW.edges(data=True)))
-        GI=Graph(dol)
+        GI = nx.Graph(dol)
         assert_nodes_equal(sorted(XGS.nodes()), sorted(GI.nodes()))
         assert_edges_equal(enone, sorted(GI.edges(data=True)))
 
         # Dict of dicts
         # with multiedges, OK
-        dod=to_dict_of_dicts(XGM)
-        GG=from_dict_of_dicts(dod,create_using=MultiGraph(),
-                              multigraph_input=True)
+        dod = to_dict_of_dicts(XGM)
+        GG = from_dict_of_dicts(dod, create_using=nx.MultiGraph(),
+                                multigraph_input=True)
         assert_nodes_equal(sorted(XGM.nodes()), sorted(GG.nodes()))
         assert_edges_equal(sorted(XGM.edges()), sorted(GG.edges()))
-        GW=to_networkx_graph(dod,create_using=MultiGraph(),multigraph_input=True)
+        GW = to_networkx_graph(dod, create_using=nx.MultiGraph(), multigraph_input=True)
         assert_nodes_equal(sorted(XGM.nodes()), sorted(GW.nodes()))
         assert_edges_equal(sorted(XGM.edges()), sorted(GW.edges()))
-        GI=MultiGraph(dod)  # convert can't tell whether to duplicate edges!
+        GI = nx.MultiGraph(dod)  # convert can't tell whether to duplicate edges!
         assert_nodes_equal(sorted(XGM.nodes()), sorted(GI.nodes()))
         #assert_not_equal(sorted(XGM.edges()), sorted(GI.edges()))
         assert_false(sorted(XGM.edges()) == sorted(GI.edges()))
-        GE=from_dict_of_dicts(dod,create_using=MultiGraph(),
-                              multigraph_input=False)
+        GE = from_dict_of_dicts(dod, create_using=nx.MultiGraph(),
+                                multigraph_input=False)
         assert_nodes_equal(sorted(XGM.nodes()), sorted(GE.nodes()))
         assert_not_equal(sorted(XGM.edges()), sorted(GE.edges()))
-        GI=MultiGraph(XGM)
+        GI = nx.MultiGraph(XGM)
         assert_nodes_equal(sorted(XGM.nodes()), sorted(GI.nodes()))
         assert_edges_equal(sorted(XGM.edges()), sorted(GI.edges()))
-        GM=MultiGraph(G)
+        GM = nx.MultiGraph(G)
         assert_nodes_equal(sorted(GM.nodes()), sorted(G.nodes()))
         assert_edges_equal(sorted(GM.edges()), sorted(G.edges()))
 
         # Dict of lists
         # with multiedges, OK, but better write as DiGraph else you'll
         # get double edges
-        dol=to_dict_of_lists(G)
-        GG=from_dict_of_lists(dol,create_using=MultiGraph())
+        dol = to_dict_of_lists(G)
+        GG = from_dict_of_lists(dol, create_using=nx.MultiGraph())
         assert_nodes_equal(sorted(G.nodes()), sorted(GG.nodes()))
         assert_edges_equal(sorted(G.edges()), sorted(GG.edges()))
-        GW=to_networkx_graph(dol,create_using=MultiGraph())
+        GW = to_networkx_graph(dol, create_using=nx.MultiGraph())
         assert_nodes_equal(sorted(G.nodes()), sorted(GW.nodes()))
         assert_edges_equal(sorted(G.edges()), sorted(GW.edges()))
-        GI=MultiGraph(dol)
+        GI = nx.MultiGraph(dol)
         assert_nodes_equal(sorted(G.nodes()), sorted(GI.nodes()))
         assert_edges_equal(sorted(G.edges()), sorted(GI.edges()))
 
     def test_edgelists(self):
-        P=path_graph(4)
-        e=[(0,1),(1,2),(2,3)]
-        G=Graph(e)
+        P = nx.path_graph(4)
+        e = [(0, 1), (1, 2), (2, 3)]
+        G = nx.Graph(e)
         assert_nodes_equal(sorted(G.nodes()), sorted(P.nodes()))
         assert_edges_equal(sorted(G.edges()), sorted(P.edges()))
         assert_edges_equal(sorted(G.edges(data=True)), sorted(P.edges(data=True)))
 
-        e=[(0,1,{}),(1,2,{}),(2,3,{})]
-        G=Graph(e)
+        e = [(0, 1, {}), (1, 2, {}), (2, 3, {})]
+        G = nx.Graph(e)
         assert_nodes_equal(sorted(G.nodes()), sorted(P.nodes()))
         assert_edges_equal(sorted(G.edges()), sorted(P.edges()))
         assert_edges_equal(sorted(G.edges(data=True)), sorted(P.edges(data=True)))
 
-        e=((n,n+1) for n in range(3))
-        G=Graph(e)
+        e = ((n, n + 1) for n in range(3))
+        G = nx.Graph(e)
         assert_nodes_equal(sorted(G.nodes()), sorted(P.nodes()))
         assert_edges_equal(sorted(G.edges()), sorted(P.edges()))
         assert_edges_equal(sorted(G.edges(data=True)), sorted(P.edges(data=True)))
@@ -200,24 +204,24 @@ def test_edgelists(self):
     def test_directed_to_undirected(self):
         edges1 = [(0, 1), (1, 2), (2, 0)]
         edges2 = [(0, 1), (1, 2), (0, 2)]
-        assert_true(self.edgelists_equal(nx.Graph(nx.DiGraph(edges1)).edges(),edges1))
-        assert_true(self.edgelists_equal(nx.Graph(nx.DiGraph(edges2)).edges(),edges1))
-        assert_true(self.edgelists_equal(nx.MultiGraph(nx.DiGraph(edges1)).edges(),edges1))
-        assert_true(self.edgelists_equal(nx.MultiGraph(nx.DiGraph(edges2)).edges(),edges1))
+        assert_true(self.edgelists_equal(nx.Graph(nx.DiGraph(edges1)).edges(), edges1))
+        assert_true(self.edgelists_equal(nx.Graph(nx.DiGraph(edges2)).edges(), edges1))
+        assert_true(self.edgelists_equal(nx.MultiGraph(nx.DiGraph(edges1)).edges(), edges1))
+        assert_true(self.edgelists_equal(nx.MultiGraph(nx.DiGraph(edges2)).edges(), edges1))
 
         assert_true(self.edgelists_equal(nx.MultiGraph(nx.MultiDiGraph(edges1)).edges(),
                                          edges1))
         assert_true(self.edgelists_equal(nx.MultiGraph(nx.MultiDiGraph(edges2)).edges(),
                                          edges1))
 
-        assert_true(self.edgelists_equal(nx.Graph(nx.MultiDiGraph(edges1)).edges(),edges1))
-        assert_true(self.edgelists_equal(nx.Graph(nx.MultiDiGraph(edges2)).edges(),edges1))
+        assert_true(self.edgelists_equal(nx.Graph(nx.MultiDiGraph(edges1)).edges(), edges1))
+        assert_true(self.edgelists_equal(nx.Graph(nx.MultiDiGraph(edges2)).edges(), edges1))
 
     def test_attribute_dict_integrity(self):
-        # we must not replace dict-like graph data structures with dicts 
-        G=OrderedGraph()
+        # we must not replace dict-like graph data structures with dicts
+        G = nx.OrderedGraph()
         G.add_nodes_from("abc")
-        H=to_networkx_graph(G, create_using=OrderedGraph())
-        assert_equal(list(H.node),list(G.node))
-        H=OrderedDiGraph(G)
-        assert_equal(list(H.node),list(G.node))
+        H = to_networkx_graph(G, create_using=nx.OrderedGraph())
+        assert_equal(list(H.node), list(G.node))
+        H = nx.OrderedDiGraph(G)
+        assert_equal(list(H.node), list(G.node))
diff --git a/networkx/tests/test_convert_pandas.py b/networkx/tests/test_convert_pandas.py
--- a/networkx/tests/test_convert_pandas.py
+++ b/networkx/tests/test_convert_pandas.py
@@ -2,9 +2,12 @@
 from nose.tools import assert_true
 
 import networkx as nx
+from networkx.testing import assert_nodes_equal, assert_edges_equal
+
 
 class TestConvertPandas(object):
-    numpy=1 # nosetests attribute, use nosetests -a 'not numpy' to skip test
+    numpy = 1  # nosetests attribute, use nosetests -a 'not numpy' to skip test
+
     @classmethod
     def setupClass(cls):
         try:
@@ -17,49 +20,70 @@ def __init__(self, ):
         import pandas as pd
 
         self.r = pd.np.random.RandomState(seed=5)
-        ints = self.r.random_integers(1, 10, size=(3,2))
+        ints = self.r.random_integers(1, 10, size=(3, 2))
         a = ['A', 'B', 'C']
         b = ['D', 'A', 'E']
         df = pd.DataFrame(ints, columns=['weight', 'cost'])
-        df[0] = a # Column label 0 (int)
-        df['b'] = b # Column label 'b' (str)
+        df[0] = a  # Column label 0 (int)
+        df['b'] = b  # Column label 'b' (str)
         self.df = df
         mdf = pd.DataFrame([[4, 16, 'A', 'D']],
-                            columns=['weight', 'cost', 0, 'b'])
+                           columns=['weight', 'cost', 0, 'b'])
         self.mdf = df.append(mdf)
 
     def assert_equal(self, G1, G2):
-        assert_true( nx.is_isomorphic(G1, G2, edge_match=lambda x, y: x == y ))
+        assert_true(nx.is_isomorphic(G1, G2, edge_match=lambda x, y: x == y))
 
     def test_from_dataframe_all_attr(self, ):
         Gtrue = nx.Graph([('E', 'C', {'cost': 9, 'weight': 10}),
-                               ('B', 'A', {'cost': 1, 'weight': 7}),
-                               ('A', 'D', {'cost': 7, 'weight': 4})])
-        G=nx.from_pandas_dataframe(self.df, 0, 'b', True)
+                          ('B', 'A', {'cost': 1, 'weight': 7}),
+                          ('A', 'D', {'cost': 7, 'weight': 4})])
+        G = nx.from_pandas_dataframe(self.df, 0, 'b', True)
         self.assert_equal(G, Gtrue)
         # MultiGraph
         MGtrue = nx.MultiGraph(Gtrue)
         MGtrue.add_edge('A', 'D', cost=16, weight=4)
-        MG=nx.from_pandas_dataframe(self.mdf, 0, 'b', True, nx.MultiGraph())
+        MG = nx.from_pandas_dataframe(self.mdf, 0, 'b', True, nx.MultiGraph())
         self.assert_equal(MG, MGtrue)
 
     def test_from_dataframe_multi_attr(self, ):
         Gtrue = nx.Graph([('E', 'C', {'cost': 9, 'weight': 10}),
-                               ('B', 'A', {'cost': 1, 'weight': 7}),
-                               ('A', 'D', {'cost': 7, 'weight': 4})])
-        G=nx.from_pandas_dataframe(self.df, 0, 'b', ['weight', 'cost'])
+                          ('B', 'A', {'cost': 1, 'weight': 7}),
+                          ('A', 'D', {'cost': 7, 'weight': 4})])
+        G = nx.from_pandas_dataframe(self.df, 0, 'b', ['weight', 'cost'])
         self.assert_equal(G, Gtrue)
 
     def test_from_dataframe_one_attr(self, ):
         Gtrue = nx.Graph([('E', 'C', {'weight': 10}),
-                               ('B', 'A', {'weight': 7}),
-                               ('A', 'D', {'weight': 4})])
-        G=nx.from_pandas_dataframe(self.df, 0, 'b', 'weight')
+                          ('B', 'A', {'weight': 7}),
+                          ('A', 'D', {'weight': 4})])
+        G = nx.from_pandas_dataframe(self.df, 0, 'b', 'weight')
         self.assert_equal(G, Gtrue)
 
     def test_from_dataframe_no_attr(self, ):
         Gtrue = nx.Graph([('E', 'C', {}),
-                               ('B', 'A', {}),
-                               ('A', 'D', {})])
-        G=nx.from_pandas_dataframe(self.df, 0, 'b',)
+                          ('B', 'A', {}),
+                          ('A', 'D', {})])
+        G = nx.from_pandas_dataframe(self.df, 0, 'b',)
         self.assert_equal(G, Gtrue)
+
+    def test_from_datafram(self, ):
+        # Pandas DataFrame
+        g = nx.cycle_graph(10)
+        G = nx.Graph()
+        G.add_nodes_from(g)
+        G.add_weighted_edges_from((u, v, u) for u, v in g.edges())
+        edgelist = nx.to_edgelist(G)
+        source = [s for s, t, d in edgelist]
+        target = [t for s, t, d in edgelist]
+        weight = [d['weight'] for s, t, d in edgelist]
+        import pandas as pd
+        edges = pd.DataFrame({'source': source,
+                              'target': target,
+                              'weight': weight})
+        GG = nx.from_pandas_dataframe(edges, edge_attr='weight')
+        assert_nodes_equal(sorted(G.nodes()), sorted(GG.nodes()))
+        assert_edges_equal(sorted(G.edges()), sorted(GG.edges()))
+        GW = nx.to_networkx_graph(edges, create_using=nx.Graph())
+        assert_nodes_equal(sorted(G.nodes()), sorted(GW.nodes()))
+        assert_edges_equal(sorted(G.edges()), sorted(GW.edges()))