【问题标题】:Avoid NaN attributes when building NetworkX graph构建 NetworkX 图时避免使用 NaN 属性
【发布时间】:2019-08-14 07:09:58
【问题描述】:

我想使用 pandas 读取包含节点及其属性的 csv 文件。并非所有节点都具有每个属性,缺少的属性只是从 csv 文件中丢失。当 pandas 读取 csv 文件时,缺失值显示为nan。我想从数据框中批量添加节点,但避免添加nan 的属性。

例如,这里是一个名为mwe.csv的示例csv文件:

Name,Cost,Depth,Class,Mean,SD,CST,SL,Time
Manuf_0001,39.00,1,Manuf,,,12,,10.00
Manuf_0002,36.00,1,Manuf,,,8,,10.00
Part_0001,12.00,2,Part,,,,,28.00
Part_0002,5.00,2,Part,,,,,15.00
Part_0003,9.00,2,Part,,,,,10.00
Retail_0001,0.00,0,Retail,253,36.62,0,0.95,0.00
Retail_0002,0.00,0,Retail,45,1,0,0.95,0.00
Retail_0003,0.00,0,Retail,75,2,0,0.95,0.00

这是我目前的处理方式:

import pandas as pd
import numpy as np
import networkx as nx

node_df = pd.read_csv('mwe.csv')

graph = nx.DiGraph()
graph.add_nodes_from(node_df['Name'])
nx.set_node_attributes(graph, dict(zip(node_df['Name'], node_df['Cost'])), 'nodeCost')
nx.set_node_attributes(graph, dict(zip(node_df['Name'], node_df['Mean'])), 'avgDemand')
nx.set_node_attributes(graph, dict(zip(node_df['Name'], node_df['SD'])), 'sdDemand')
nx.set_node_attributes(graph, dict(zip(node_df['Name'], node_df['CST'])), 'servTime')
nx.set_node_attributes(graph, dict(zip(node_df['Name'], node_df['SL'])), 'servLevel')

# Loop through all nodes and all attributes and remove NaNs.
for i in graph.nodes:
    for k, v in list(graph.nodes[i].items()):
        if np.isnan(v):
            del graph.nodes[i][k]

它有效,但它很笨重。有没有更好的方法,例如在添加节点时避免nans,而不是之后删除nans?

【问题讨论】:

    标签: python pandas csv networkx nan


    【解决方案1】:

    将 csv 导入 Pandas 时使用 keep_default_na

    pd.read_csv('data.csv', keep_default_na=False)
    

    Get pandas.read_csv to read empty values as empty string instead of nan

    【讨论】:

      【解决方案2】:

      在这种情况下,您可以利用 Pandas 的力量进行竞标。所以,我创建了这个函数,它将你的带有两个键和值列的 DataFrame 转换为一个系列,然后使用 NaN 删除元素,最后将其更改为字典

      def create_node_attribs(key_col, val_col):
          # Upto you if you want to pass the dataframe as argument
          # In your case, since this was the only df, I only passed the columns
          global node_df
          return Series(node_df[val_col].values,
                        index=node_df[key_col]).dropna().to_dict()
      

      这是完整的代码

      import pandas as pd
      import networkx as nx
      from pandas import Series
      
      node_df = pd.read_csv('mwe.csv')
      
      graph = nx.DiGraph()
      
      def create_node_attribs(key_col, val_col):
          # Upto you if you want to pass the dataframe as argument
          # In your case, since this was the only df, I only passed the columns
          global node_df
          return Series(node_df[val_col].values,
                        index=node_df[key_col]).dropna().to_dict()
      
      graph.add_nodes_from(node_df['Name'])
      nx.set_node_attributes(graph, create_node_attribs('Name', 'Cost'), 'nodeCost')
      nx.set_node_attributes(graph, create_node_attribs('Name', 'Mean'), 'avgDemand')
      nx.set_node_attributes(graph, create_node_attribs('Name', 'SD'), 'sdDemand')
      nx.set_node_attributes(graph, create_node_attribs('Name', 'CST'), 'servTime')
      nx.set_node_attributes(graph, create_node_attribs('Name', 'SL'), 'servLevel')
      

      使用代码链接到Google Colab Notebook

      另外,see this answer,了解有关当前所用方法的时间比较的更多信息。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2019-12-07
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2013-03-18
        • 2017-12-06
        相关资源
        最近更新 更多