如何从包含单行所有关系的csv文件中获取relationshipdata?

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

我想在networkx中为植物建立关系图。在我的csv文件中,这些工厂的所有数据都包含在每个工厂的单行中。例如:植物编号,植物名称,伴侣植物,拮抗剂。现在我想要networkx图,其中植物名称位于中间并且与所有伴侣植物有关系(每个伴侣植物是节点,主植物具有所有这些伴生植物的边缘)。

对于苹果,数据是这样的:

1,apple,"pearl,strawberry,onion,potato","rose,cabbage,dill"

我知道如何制作图表本身是因为我使用不同的旧csv文件,其中有植物和每个伴侣在自己的行上像这样:

apple,pearl
apple,strawberry
apple,onion
apple,potato

我想知道如何从这个新的csv中读取和获取边缘,其中所有同伴在单行上用逗号分隔。有什么建议?

python csv graph relationship networkx
2个回答
1
投票

您不应该像','那样拆分CSV行,如另一个问题中所提出的那样。您在CSV中的变量包含',',因此您将得到不正确的结果。只需使用pandas.read_csv()

df = pd.read_csv('WAKA.csv', header=None)


    0   1       2                               3
0   1   apple   pearl,strawberry,onion,potato   rose,cabbage,dill
1   2   apple1  pearl,strawberry,onion,potato   rose,cabbage,dill

然后迭代行,得到第1列,在第2列中用','拆分字符串并将其添加到你的networkx图中:


for l in df.iterrows():   # Iterate through dataframe rows
    G.add_edges_from(     # Add edges to graph
        (l[1][1], fruit)  # It is the edge: element from column 1 and splitted fruit
        for fruit in l[1][2].strip('"').split(',')  # Crop '"' and split by ','
    )

然后画它:

nx.draw(
    G,
    node_size=3500,
    font_size=40,
    labels={n: n for n in G.nodes}
)

enter image description here


0
投票

我对NetworkX了解不多,但您可以将所有信息提取到字典中并使用它来填充NetworkX图。

plants = {}

with open('plant-data.csv') as fd:
    for line in fd:
        plant = line.split(',')

        plant_number = line[0]
        plant_name = line[1]
        plant_companions = line[2]
        plant_antagonists = line[3]

        plants[plant_name] = (plant_number, plant_companions, plant_antagonists)

要获得apple的所有同伴,您只需访问plants["apple"][1]

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