shifting right in for loop over indices in python

shifting right in for loop over indices in python

Content Index :

shifting right in for loop over indices in python
Tag : python , By : Antony Briggs
Date : November 24 2020, 05:44 AM

No Comments Right Now !

Boards Message :
You Must Login Or Sign Up to Add Your Comments .

Share : facebook icon twitter icon

Loop backwards using indices in Python?

Tag : python , By : mediafarm
Date : March 29 2020, 07:55 AM
Does that help Try range(100,-1,-1), the 3rd argument being the increment to use (documented here).
("range" options, start, stop, step are documented here)

Consecutive indices of a Python list in for loop, without specifying indices

Tag : python , By : alexmajy
Date : March 29 2020, 07:55 AM
I wish this help you I'm fond of the pairwise recipe as listed in the docs to the itertools module:
def pairwise(iterable):
    "s -> (s0,s1), (s1,s2), (s2, s3), ..."
    a, b = tee(iterable)
    next(b, None)
    return izip(a, b)
for x, x_next in pairwise(the_list):
for x, x_next in zip(the_list, the_list[1:]):

shifting indices to the left in a struct unsorted array

Tag : cpp , By : Ronnie Carlin
Date : March 29 2020, 07:55 AM
I think the issue was by ths following , What that's doing is removing that item from its position in the array, by going through all remaining items and moving them one closer (and then decrementing the count in the end.)
Simplified example:
Array position :   [0]  [1]  [2]  [3]  [4]  [5]  [6]  [7]  [8]  [9]
Values in array:    a    l    p    h    a    b    e    t    i    c
Array position :   [0]  [1]  [2]  [3]  [4]  [5]  [6]  [7]  [8]  [9]
Values in array:    a    l    p    h    a    e    t    i    c    
for (mlsCounter = 0; ((mlsCounter < count) && (mlsDelete == NOT_FOUND));
                             mlsCounter++) {

             if (houseData[mlsCounter].mlsNum == targetMLS) {

                mlsDelete = houseData[mlsCounter].mlsNum; 

                houseData[mlsCounter].mlsNum = 0; 
                houseData[mlsCounter].price = 0;
                houseData[mlsCounter].type = 0;


   for (move = mlsCounter;move < count - 1; move++){

Shifting data in 2d array through shifted indices

Tag : python , By : fedorafennec
Date : March 29 2020, 07:55 AM
help you fix your problem I implemented a version of pythonic that replicates nonpythonic with some masking and index fiddling - see below. By the way I think the "new" indices should be the ones corresponding to the new array, rather than the old ones, but I've left it as in your existing function.
The main thing to realise is that in your attempt in the question, your conditions
ind_y_good = np.where(iy>=0) and np.where(iy<ny)
ind_x_good = np.where(ix>=0) and np.where(ix<nx)
import numpy as np
import matplotlib.pyplot as plt
from matplotlib import mpl

def nonpythonic(previous_data, ix, iy, nx, ny):
    #this works, but is slow (for large arrays)        
    new_data = np.zeros((ny,nx))
    for j in xrange(ny):
        for i in xrange(nx):
            #go through each item, check if it is within the bounds
            #and assign the data to the new_data array
            i_new = ix[j,i]
            j_new = iy[j,i]
            if ((i_new>=0) and (i_new<nx) and (j_new>=0) and (j_new<ny)):

    return new_data

def pythonic(previous_data, ix, iy):

    ny, nx = previous_data.shape
    iy_old, ix_old = np.indices(previous_data.shape)

    # note you must apply the same condition to both
    # index arrays
    valid = (iy >= 0) & (iy < ny) & (ix >= 0) & (ix < nx)

    new_data = np.zeros((ny,nx))

    new_data[iy_old[valid], ix_old[valid]] = previous_data[iy[valid], ix[valid]]
    return new_data

def main():
    #some 2D array:
    nx = 20
    ny = 30    
    #array indices:
    iy, ix = np.indices((ny,nx))
    #modify indices (shift):
    iy = iy + 1
    ix = ix - 4
    #create some out of range indices (which might happen in my real scenario)
    iy[0,2:7] = -9999
    ix[0:3,-1] = 6666

    #some previous data which is the basis for the new_data:
    previous_data = np.ones((ny,nx))
    previous_data[2:8,10:20] = 2
    data_nonpythonic = nonpythonic(previous_data, ix, iy, nx, ny)
    data_pythonic = pythonic(previous_data, ix, iy)

    new_data = data_nonpythonic
    ef, axar = plt.subplots(1,2)
    im = axar[0].pcolor(previous_data, vmin=0,vmax=2)
    ef.colorbar(im, ax=axar[0], shrink=0.9)
    im = axar[1].pcolor(new_data, vmin=0,vmax=2)
    ef.colorbar(im, ax=axar[1], shrink=0.9)
    print(np.allclose(data_nonpythonic, data_pythonic))

if __name__ == "__main__":

Shifting datatable rows by indices

Tag : r , By : Chaz
Date : March 29 2020, 07:55 AM
around this issue While trying to answer this question on Stack Overflow, I ran into my own separate question, which I am unable to solve myself. However, I am really curious to find an efficient solution for my problem. I initially posted this as an answer to that question, but since it caused confusion I think it is a better decision to post this question separately: , You could try:
dat[, c("value1.shift", "value2.shift") := list(dat$value[shift_id], dat$value2[shift_id])]

 > dat
   value value2 value1.shift value2.shift
1:     1      1            1            1
2:     2      2            2            2
3:     3      3            3            3
4:     4      4           NA           NA
5:     5      5            4            4
6:     6      6           NA           NA
7:     7      7            5            5
dat[, paste0(names(dat)[grepl("value", names(dat))], ".shift") := lapply(.SD, `[`, shift_id), .SDcols = grep("value", names(dat))]
Related Posts Related QUESTIONS :
  • Is there a way to remove specific strings from indexes using a for loop?
  • select multiple tags by position in beautifulSoup
  • pytest: getting AttributeError: 'CaptureFixture' object has no attribute 'readouterror' capturing stdout
  • Shipping PyGObject/GTK+ app on Windows with MingW
  • Python script to deduplicate lines in multiple files
  • How to prevent window and widgets in a pyqt5 application from changing size when the visibility of one widget is altered
  • How to draw stacked bar plot from df.groupby('feature')['label'].value_counts()
  • Python subprocess doesn't work without sleep
  • How can I adjust 'the time' in python with module Re
  • Join original np array with resulting np array in a form of dictionary? multidimensional array? etc?
  • Forcing labels on histograms in each individual graph in a figure
  • For an infinite dataset, is the data used in each epoch the same?
  • Is there a more efficent way to extend a string?
  • How to calculate each single element of a numpy array based on conditions
  • How do I change the width of Jupyter notebook's cell's left part?
  • Measure distance between lat/lon coordinates and utm coordinates
  • Installing megam for NLTK on Windows
  • filter dataframe on each value of a samn column have a specific value of another column in Panda\Python
  • Threading with pubsub throwing AssertionError: 'callableObj is not callable' in wxPython
  • Get grouped data from 2 dataframes with condition
  • How can I import all of sklearns regressors
  • How to take all elements except the first k
  • Whats wrong with my iteration list of lists from csv
  • Tensorflow Estimator API save image summary in eval mode
  • How to Pack with PyQt - how to make QFrame/Layout adapt to content
  • How do I get certain Time Range in Python
  • python doubly linked list - insertAfter node
  • Open .h5 file in Python
  • Joining a directory name with a binary file name
  • python, sort list with two arguments in compare function
  • Is it possible to print from Python using non-ANSI colors?
  • Pandas concat historical data using date minus some number of days
  • CV2: Import Error in Python OpenCV
  • Is it possible to do this loop in a one-liner?
  • invalid literal for int() with base 10: - django
  • Why does my code print a value that I have not assigned as yet?
  • the collatz func in automate boring stuff with python
  • How to find all possible combinations of parameters and funtions
  • about backpropagation deep neural network in tensorflow
  • Sort strings in pandas
  • How do access my flask app hosted in docker?
  • Replace the sentence include some text with Python regex
  • Counting the most common element in a 2D List in Python
  • logout a user from the system using a function in python
  • mp4 metadata not found but exists
  • Django: QuerySet with ExpressionWrapper
  • Pandas string search in list of dicts
  • Decryption from RSA encrypted string from sqlite is not the same
  • need of maximum value in int
  • a list of several tuples, how to extract the same of the first two elements in the small tuple in the large tuple
  • Display image of 2D Sinewaves in 3D
  • how to prevent a for loop from overwriting a dictionary?
  • How To Fix: RuntimeError: size mismatch in pyTorch
  • Concatenating two Pandas DataFrames while maintaining index order
  • Why does this not run into an infinite loop?
  • Python Multithreading no current event loop
  • Element Tree - Seaching for specific element value without looping
  • Ignore Nulls in pandas map dictionary
  • How do I get scrap data from web pages using beautifulsoup in python
  • Variable used, golobal or local?
  • shadow
    Privacy Policy - Terms - Contact Us © scrbit.com