Iterate through a pandas dataframe to get a specific output [closed]

2024/10/5 15:08:23

I have a dataframe which I want to iterate to get a specific result.

Portion of the dataframe df (the name of the columns are guid1 and guid2) : DataSet

 guid1  guid2A865   OR4A875   OR4OR4    JN1397JN1400 JN1401JN1402 DEL131KS-Unset  AND1

Interpretation : Both A865 and A875 are connected to OR4 and OR4 is then connected to JN1397 (it's a representation of a logical diagram). My goal here is to iterate through the dataframe (to verify if there is any connections) to get a string result (as follows) in which I interpret the different connections:

A865, A875, OR4, JN1397

I already posted this question and it has been closed for lack of clarity, I really hope it's clear enough now because I really need some help here..

Answer

You could use networkx to handle your graph.

This is how it looks (showing as directed graph, but using an undirected graph later):

enter image description here

You can create the graph using:

import networkx as nxG = nx.from_pandas_edgelist(df, source='guid1', target='guid2')

Then keep the subgraph that contains your initial node:

start = df['guid1'].iloc[0] # 'A865'keep = nx.node_connected_component(G, start)
# {'A865', 'A875', 'JN1397', 'OR4'}

If you really want the pseudo-path in original order of the DataFrame:

key = {v: k for k,v in enumerate(df['guid1'].drop_duplicates())}
# {'A865': 0, 'A875': 1, 'OR4': 2, 'JN1400': 3, 'JN1402': 4, 'Unset': 5}path = ' -> '.join(sorted(keep, key=lambda x: key.get(x, float('inf'))))

output: 'A865 -> A875 -> OR4 -> JN1397'

https://en.xdnf.cn/q/120193.html

Related Q&A

Detect if you click inside a box in Python Zelle graphics

I have created a dice betting game. When my code is run, there is a "CLICK TO ROLL" button. Currently, if you click anywhere on the screen, the dice will roll. How can I make it so the progra…

Nested Triangle in Python

My assingmentAt each level the complete triangle for the previous level is placed into an extra outer triangle. The user should be asked to input the two characters to be used and the width of the inne…

How to fix cannot open file Test.py: [Errno2] No such file or directory?

I tried to run a python script which does not exist in current folder, for exampleC:\>python Test.pypython:cant open file Test.py:[Errno2] No such file or directoryI have to specify the absolute pat…

Highlight cells in a column in google spreadsheet when the value above a threshold with python

Here is a simplified example of my codes and the screenshot of the results I want to get in google spreadsheet. I hope to either save the dataframe style to google spreadsheet as applying table style t…

cannot concatenate str and file objects : Python error

I have Following piece of code: for src_filename, src_code in src_dict.iteritems(): try: set.dependencies = subprocess.check_output(unifdef -s /home/c/maindir/folder/ +src_filename, shell=True) except…

Run python script from html button submit

i have a code input data to txt file :<form action="proses.php" method="post">Nomor Polisi : <br><input type="text" name="nopol"><br><…

Reading log files in python

I have a log file (it is named data.log) containing data that I would like to read and manipulate. The file is structured as follows:#Comment line 1 #Comment line 2 1.00000000,3.02502604,343260.6865…

Return more than one value in python function [duplicate]

This question already has answers here:How can I use `return` to get back multiple values from a loop? Can I put them in a list?(2 answers)Closed 1 year ago.I was trying to use *args with a for loop …

Python: Making a class to use complex numbers

I am currently trying to write a program that deals with complex numbers. I have to use classes and methods. I am trying to be able to add, subtract, multiply etc., complex numbers, as well as compare …

Return does not return anything in Spyder. It works fine with other IDE

I just moved to spyder for Python and the return function doesnt seem to work: def test():return 2 test()The IPython console is empty. If I use print instead of return it works fine. Any idea? I use p…