构建NetworkX图时,请避免使用NaN属性

问题描述 投票:1回答:1

我想使用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个回答
1
投票

在这种情况下,您可以利用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,有关当前使用的方法的时间比较的更多信息。

© www.soinside.com 2019 - 2024. All rights reserved.