logo
down
shadow

Python - Iterative self cross referencing


Python - Iterative self cross referencing

By : StevenLavinske
Date : November 22 2020, 10:40 AM
I wish this helpful for you I have a bit of a logical challenge. I have a single table in excel that contains an identifier column and a cross reference column. There can be multiple rows for a single identifier which indicates multiple cross references. (see basic example below)
code :
t = [
    ["a1","a2"],
    ["a1","a3"],
    ["a1","ax"],
    ["ax","b1"],
    ["ax","bx"],
    ["bx","b3"]
]

import itertools
def find_matches(t,key):
    return list(itertools.chain(*[[v] if not v.endswith("x") else find_matches(t,v) for k,v in t if k == key]))

print find_matches(t,"a1")
t = [
    ["a1","a2"],
    ["a1","a3"],
    ["a1","ax"],
    ["ax","b1"],
    ["ax","bx"],
    ["bx","b3"]
]
class MyGraph:
    def __init__(self,adjacency_table):
        self.table = adjacency_table
        self.graph = {}
        for from_node,to_node in adjacency_table:
            if from_node in self.graph:
                self.graph[from_node].append(to_node)                
            else:
                self.graph[from_node] = [to_node]
        print self.graph
    def find_leaves(self,v):
        seen = set(v)
        def search(v):
            for vertex in self.graph[v]:
                if vertex in seen:
                    continue
                seen.add(vertex)
                if vertex in self.graph:
                    for p in search(vertex):
                       yield p
                else:
                    yield vertex
        for p in search(v):
            yield p



print list(MyGraph(t).find_leaves("a1"))#,"a1")


Share : facebook icon twitter icon
Python Pandas Lookup/Cross Referencing

Python Pandas Lookup/Cross Referencing


By : Ying-Chieh Jay Huang
Date : March 29 2020, 07:55 AM
it helps some times I have two data frames: , For (i) you just need to specify right join, and fill null values:
code :
>>> pd.merge(df1, df2, how='right').fillna(0)
    word  score
0  laugh      7
1  frown     -3
2   play      0
>>> def grpavg(ws):
...     i = df1['word'].isin(ws)
...     return df1.loc[i, 'score'].sum() / len(ws)
... 
>>> df3['avg-score'] = df3['words'].str.split().map(grpavg)
>>> df3
                  words  avg-score
0             frown cry      -5.50
1           laugh smile       4.50
2            play laugh       3.50
3  cry laugh play smile       0.25
>>> def grpavg(ws, df):
...     i = df['word'].isin(ws)
...     return df.loc[i, 'score'].sum() / len(ws)
... 
>>> from functools import partial
>>> f = partial(grpavg, df=df1)
>>> df3['avg-score'] = df3['words'].str.split().map(f)
>>> df3
                  words  avg-score
0             frown cry      -5.50
1           laugh smile       4.50
2            play laugh       3.50
3  cry laugh play smile       0.25
can there be 'cross-referencing' generators in Python?

can there be 'cross-referencing' generators in Python?


By : user3856341
Date : March 29 2020, 07:55 AM
should help you out Imagine the following piece of code which generates a list of file sizes from the current directories' files: , You can do it like this:
code :
_sizes = [
    getsize(join(_base, _file))
    for _base, _dirs, _files in os.walk('.')
    for _file in _files
]
_sizes = (
    getsize(join(_base, _file))
    for _base, _dirs, _files in os.walk('.')
    for _file in _files
)
Cross Referencing Lists in Python

Cross Referencing Lists in Python


By : samathon
Date : March 29 2020, 07:55 AM
To fix this issue You can loop through each list in list_1 and check if the input is in one. If it is, you can print the corresponding index of list_2 (assuming it is composed only of single values), which you obtain by using enumerate in the loop.
code :
input = 1
for idx,i in enumerate(list_1):
    if input in i:
        return list_2[idx]
Cross referencing two csv files in python

Cross referencing two csv files in python


By : Karam Al-Raawy
Date : March 29 2020, 07:55 AM
To fix this issue The first thing you need to be aware of is that you can't update the file you are reading. Textfiles (which include .csv files) don't work like that. So you have to read the whole of Destinations.csv into memory, and then write it out again, under a new name, but skipping the rows you don't want. (You can overwrite your input file, but you will very quickly discover that is a bad idea.)
code :
import csv

blacklist_rows = []
with open('Black List.csv', 'r') as bl:
    reader = csv.reader(bl)
    for line in reader:
        blacklist_rows.append(line)

destination_rows = []
with open('Destinations.csv', 'r') as dest:
    readern = csv.reader(dest)
    for line in readern:
        destination_rows.append(line)
with open('FilteredDestinations.csv', 'w') as output:
    writer = csv.writer(output)
    for r in destination_rows:
        if not r:   # trap for blank rows in the input
            continue
        if r *matches something in blacklist_rows*: # you have to code this
            continue
        writer.writerow(r)
Cross-referencing between two lists in Python?

Cross-referencing between two lists in Python?


By : Tiago Vieira
Date : October 04 2020, 09:00 PM
it helps some times You can use setdefault to accumulate the shopping list like:
Code
code :
users = {x['id']: x for x in a}
for x in b:
    user = users[x['uid']]
    user.setdefault('shoppinglist', []).append(x['item'])
result = [users[i['id']] for i in a]
a = [
    {
        "id": 1,
        "name": "John Mark",
        "alias": "Batman",
    },
    {
        "id": 2,
        "name": "Luke Ben",
        "alias": "Spider",
    }
]

b = [
    {
        "uid": 1,
        "item": "eggs",
        "completed": False
    },
    {
        "uid": 1,
        "item": "milk",
        "completed": False
    },
    {
        "uid": 2,
        "item": "bread",
        "completed": False
    },
    {
        "uid": 2,
        "item": "cheese",
        "completed": True
    }
]

users = {x['id']: x for x in a}
for x in b:
    user = users[x['uid']]
    user.setdefault('shoppinglist', []).append(x['item'])
result = [users[i['id']] for i in a]

print(result)
[
    {'id': 1, 'name': 'John Mark', 'alias': 'Batman', 'shoppinglist': ['eggs', 'milk']}, 
    {'id': 2, 'name': 'Luke Ben', 'alias': 'Spider', 'shoppinglist': ['bread', 'cheese']}
]
Related Posts Related Posts :
  • Return new instance of subclass when using methods inherited from parent class in Python
  • Which function in django.contrib.auth creates the default model permissions?
  • Formatting text in tabular form with Python
  • How to determine the first day of a month in Python
  • Error while converting date to timestamp in python
  • Python string iterations
  • Is there any file number limitation when you select multiple files with wxFileDialog?
  • Errors with Matplotlib when making an executable with Py2exe (Python)
  • Django Haystack - Indexing single field
  • Go Pro Hero 3 - Streaming video over wifi
  • Appending a column in .csv with Python/Pandas
  • How to change my result directory in Robot framework using RIDE?
  • problem with using pandas to manipulate a big text file in python
  • python-magic module' object has no attribute 'open'
  • Where goes wrong for this High Pass Filter in Python?
  • Why inserting keys in order into a python dict is faster than doint it unordered
  • flann index saving in python
  • Create new instance of list or dictionary without class
  • How can I easily convert FORTRAN code to Python code (real code, not wrappers)
  • Address of lambda function in python
  • Python adding space between characters in string. Most efficient way
  • python http server, multiple simultaneous requests
  • Disguising username & password on distributed python scripts
  • Post GraphQL mutation with Python Requests
  • Why doesnt pandas create an excel file?
  • Rolling comparison between a value and a past window, with percentile/quantile
  • How to avoid repetitive code when defining a new type in python with signature verification
  • How to configure uWSGI in order to debug with pdb (--honour-stdin configuration issue)
  • In Python, how do you execute objects that are functions from a list?
  • Python- Variable Won't Subtract?
  • Processing Power In Python
  • Python 2.7.2 - Cannot import name _random or random from sys
  • Why doesn't the Python sorted function take keyword order instead of reverse?
  • Make a function redirect to other functions depending on a variable
  • get_absolute_url in django-categories
  • Monitoring non-Celery background task with New Relic in Python
  • Feature selection with LinearSVC
  • LSTM - Predicting the same constant values after a while
  • Test the length of elements in a list
  • Django: render radiobutton with 3 columns, cost column must change according to size & quantity selected
  • Python class attributes vs global variable
  • sys.stdout.writelines("hello") and sys.stdout.write("hello")
  • is ndarray faster than recarray access?
  • Python - search through directory trees, rename certain files
  • GAE: How to build a query where a string begins with a value
  • TypeError: __init__() takes at least 2 arguments (1 given)
  • Overriding and customizing "django.contrib.auth.views.login"
  • Django : Redirect to a particular page after login
  • Python search and copy files in directory
  • pretty printing numpy ndarrays using unicode characters
  • Frequent pattern mining in Python
  • How can I make a set of functions that can be used synchronously as well as asynchronously?
  • Convert one dice roll to two dice roll
  • count occourrence in a list
  • Writing an If condition to filter out the first word
  • to read file and compare column in python
  • Install python-numpy in the Virtualenv environment
  • `.select_by_visible_text()` is failed to select element?
  • Unable to send data multiple requests in a single connection — socket error
  • Pandas HDFStore unload dataframe from memory
  • shadow
    Privacy Policy - Terms - Contact Us © ourworld-yourmove.org