Questions tagged [itertools]
A standard library module for Python with utilities for iterables. Also add the python tag for increased visibility.
2,844
questions
-1
votes
3
answers
35
views
List of dictionaries to summarise [closed]
There is a list of dictionaries:
given_list = [
{"cat_id": 1, "category": "red", "items": 1},
{"cat_id": 1, "category": "red&...
2
votes
3
answers
43
views
How to interlace an iterator with itself from the end?
I have an iterator in the form 0..=63, i.e.
0 1 2 3 4 ... 59 60 61 62 63.
Its .count() is 64.
How would I get the following iterator:
0 63 1 62 2 61 3 60 4 59 ...
(of course independent of the items ...
0
votes
0
answers
22
views
Combinatorics/Linear Integer Programming problem
I am trying to solve an old problem I had but I can't find an algorithm (I feel like it is recursive) or ideally an itertools solution.
Given an integer number n return all combinations m of given ...
0
votes
1
answer
56
views
Insert 1D array into a 2D array
I am trying to insert a column into a 2D array.
Currently I have a 2D array generated using itertools.
sample_points=[-1.5, -.8]
base_points = itertools.combinations_with_replacement(sample_points, 3)
...
0
votes
3
answers
30
views
Listing Column Names with Itertools
I have this Dataframe:
STATE CITY TAX_C MATERIAL IG LIMIT
0 TX DALLAS 1 CARP 0 5
1 TX DALLAS 1 BLAY 0 10
And I've created a loop using ...
1
vote
3
answers
70
views
How can I search for sub-groups of dataframe that contains specific pairs of data?
I have a dataset which contains orders, and items in those orders. What I want to find is which item pairs exist together in which group. For example, I want to find orders which has 6395477 and ...
0
votes
1
answer
22
views
why does my itertools.combinations content disappear as soon as I start a loop? [duplicate]
Here is my python codes for constructing image pairs from a list of images then loop through them:
from itertools import combinations
import os
root = "/root/code/set1/"
folders = "...
0
votes
1
answer
59
views
Itertool for python dictionary summary [closed]
I have a python dictionary with identical structure for all person:
game_score = {
"Brian": {game1: 1, game2: 0, game3: 5, game4: 1},
"David": {game1: 2, game2: 1, game3: 0,...
0
votes
0
answers
47
views
Permutations on 2D Array via itertools
I want to find all combinations of a n sized dataframe multiplied by a list.
import pandas as pd
df = pd.DataFrame({'Asset_1':(1,1),
'Asset_2': (1,1),
'Asset_n':...
1
vote
0
answers
71
views
Faster way to multiply all columns in pandas dataframe by itertools combinations
Is there a faster way to multiply all columns in a pandas dataframe with itertools combinations (by any means in python/pandas) by async numba etc
import pandas as pd
df = pd.DataFrame(data=[[312, 345,...
2
votes
1
answer
35
views
python itertools dont load files into memory
I have some what big files and I'm trying to get all combinations with this code
for text1, text2 in itertools.product(open('text1.txt'), open('text2.txt')):
t3 = (text1.strip() + text2.strip())
...
0
votes
0
answers
19
views
Pycharm install modules not recognised in code lines
I have installed my modules in my pycharm project and my code was working perfectly, but since two days ago, i am not sure what the happened, but in my code lines the modules are not recognised.
...
2
votes
1
answer
59
views
Find and eliminate pair reciprocals from data in python
This a puzzling one.
I am refactoring some code, so key-objective is/was to keep things simple.
The piece of code is supposed to locate existing reciprocal pairs in the date, so I can process them (in ...
1
vote
2
answers
52
views
Generate all multiplicative (product) combinations of columns in a pandas dataframe
I would like to generate all 2-way (and possibly 3-way) "multiplicative" combinations (i.e., column1 x column2, column2 x column3, column1 x column3, column1 x column 2 x column3, etc) of a ...
-1
votes
1
answer
34
views
Is there a way use itertools.product as a list?
The title might not be worded the right way, but I've got a function that takes a list as an input and outputs a value. Let's say I want to iterate the function over all possible combinations of a ...
0
votes
1
answer
25
views
Filter works strangely together with product
So, i have this code:
from itertools import product
data = []
for _ in range(1, 3):
for elm in product('01', repeat=_):
data += [''.join(elm)]
print(data)
And Output:
['0', '1', '00', '...
1
vote
1
answer
46
views
Itertools combinations: How to get the ids of the first fitting value combination
I have a record with a unique ID and an associated value in EURO.
Now I want to get the first combination of values that matches a value I defined.
So far I only get the combination of the values, ...
1
vote
1
answer
32
views
Python Pandas Concatenate Combinations All Columns Dynamically
COL_A
COL_B
COL_C
PRODUCT_1
UK
1/1/2021
I want to have a table that contains the result
COL_A
COL_B
COL_C
COL_A_COL_B_COL_C
COL_A_COL_B
COL_A_COL_C
COL_B_COL_C
PRODUCT_1
UK
1/1/2021
PRODUCT_1UK1/1/...
0
votes
1
answer
28
views
Python: How to pass output of the map function as arguments
I need to pass some arguments to the starmap_async function. I have a list my_list that has different values in it and some constants that are repeated. I have a way to pass the arguments as bellow:
...
0
votes
1
answer
57
views
iterrows faster alternative if data cannot be vectorized
I am having a performance issue while implementing iterrows().
My code is something like
for _, row in df.iterrows():
row["new_col"] = \
df.apply(lambda x:some_func(row["...
-1
votes
0
answers
27
views
How to sum a map object without converting to list?
I am trying to run a Monte Carlo simulation in python and it is currently using a for loop. However, the for loops take a very long to run when the number of runs is greater than 10^8. Therefore, I am ...
1
vote
2
answers
37
views
How to get unique pair from nested loop in Python
I am trying to find correlations between dataframe columns using nested loop.
import itertools
for col1 in df.columns:
for col2 in df.columns:
if col1!=col2 and col1 not in (["Country&...
0
votes
0
answers
9
views
Optimize the creation of a list from others without memory problems
I have a list of "cases" and a list of "sessions", I need to generate a list of tuples, called "disjunctions", with each element containing three elements of the form: (...
0
votes
0
answers
32
views
Is there a way to resize a matrix (list of lists) using itertools?
I'm modifying some code that generates 2D barcodes to provide "zoom" functionality.
Each barcode is represented by a matrix (list of lists) in Python.
Zoom is provided by repeating each ...
0
votes
0
answers
6
views
How do i get the first 1,5 millions sentences generated by itertools permutation with a generator
i have a list comprehension which generates sentences with one to seventeen words by selecting the words from a list of 49623 words. So here's the code to generate the sentences:
import itertools
...
1
vote
1
answer
27
views
How to group numbers between two occurences of a number using itertools.groupby
I have a list that looks like this -
nums = [0,0,0,0,1,1,2,3,4,5,6,0,0,0,0,1,2,3,4,5,6,0,0,0,0]
I want to get the numbers between the 0s in the list. For this, I used the code below -
groups = list(...
3
votes
3
answers
111
views
Python combinations of elements in dict
I have a bunch of dicts like the one below (some can be quite large):
V = {
0: [823, 832, 1151, 1752, 2548, 3036],
823: [832, 1151, 1752, 2548, 3036, 3551],
832: [1151, 1752, 2548, 3036, ...
-1
votes
2
answers
20
views
Formatting print from itertools product
I am trying to print a list of every combination of a certain set of characters, I am using Product from itertools to do that. I have code that works for the printing of every set of characters, but, ...
0
votes
1
answer
79
views
How to use multiprocessing pool.starmap with multiple arguments
I have a question.. for using Pool.starmap..
p1 = pd.dataframe(example1)
p2 = pd.dataframe(example2)
pairs = itertools.product(p1.iterrows(), p2.iterrows())
pairs_len = len(p1) * len(p2)
tpairs = ...
2
votes
1
answer
33
views
Use dask for an out of core conversion of iterable.product into a numpy/dask array (create a matrix of every permutation with repetition)
I am looking to create a matrix (numpy array of numpy arrays) of every permutation with repetition (I want to use it for matrix multiplication later on). Currently the way I am doing it, I first ...
0
votes
2
answers
33
views
Optimizing finding a string that matches the characters in a substring in any order?
Assuming a list as follows:
list_of_strings = ['foo', 'bar', 'soap', 'sseo', 'spaseo', 'oess']
and a sub string
to_find = 'seos'
I would like to find the string(s) in the list_of_strings that:
Have ...
1
vote
2
answers
71
views
How to iterate over two sorted lists in largest pairs order in Python
I have two sorted iterables, e.g.:
a = [C, B, A]
b = [3, 2, 1]
I want to generate a list of all possible pairs, combining the largest (lowest index) pairs first. Largest means all combinations of ...
0
votes
3
answers
65
views
Iterating through integers not found in a list of ranges in Python
So, I have a function which outputs a list of ranges, e.g. [range(1,5),range(8,13)]. I need to iterate through those integers which are not in a range in this list. For example, using the previous ...
0
votes
1
answer
35
views
Using a column of values to create a counter for a variable sequential number column
I currently have a pandas dataframe with some columns. I'm looking to build a column, Sequential, that lists what iteration is recorded at that part of the cycle. I'm currently doing this using ...
1
vote
0
answers
66
views
Generate the feasible list of combinations
I have used the following function to generate fund combinations in a portfolio. For example, I have four funds in the portfolio. The incremental change of each fund is 5. The range of allocations for ...
1
vote
1
answer
83
views
Can I use itertools.count to add values in a column, resetting at a certain point?
I'm trying to create a list of timestamps from a column in a dataframe, that resets after a certain time to zero. So, if the limit was 4, I want the count to add up the values of the column up to ...
0
votes
1
answer
60
views
Parsing an iterable without listifying each chunk
Suppose I want to achieve a splitting of a Python iterable, without listifying each chunk, similar to itertools.groupby, whose chunks are lazy. But I want to do it on a more sophisticated condition ...
-1
votes
2
answers
63
views
Python - itertools.groupby 2
Just having trouble with itertools.groupby. Given a list of dictionaries,
my_list= [
"AD01", "AD01AA", "AD01AB", "AD01AC", "AD01AD","AD02", ...
1
vote
3
answers
57
views
Change iteration rate on itertools
I have this iteration count using iter tools:
for i in itertools.count(start=2**68):
And I want it to bump up an exponent every time (68,69,70,71,...). Is there support for this in itertools? I have ...
0
votes
4
answers
46
views
Iterator to reverse a for loop's order of execution?
I have been searching the docs for itertools, as well as SO for a while now and have not yet found what I'm looking for. I'm hoping to reverse the order of execution of a for loop so the following ...
0
votes
2
answers
71
views
How to handle 'NoneType' object is not iterable
I'm facing this issue on my code that was working until a couple of days ago but from today is stopped working.
The issue is related to the combinations task from itertools as follow:
from itertools ...
0
votes
1
answer
191
views
How to combine two vectors of references without consuming an iterator?
I want to combine two reference vectors and convert them into a vector of values without consuming an iterator.
Situation:
Generate vectors by iterating over specific combinations. (2 elements from ...
2
votes
2
answers
88
views
Python itertools.groupby with dictionaries with multiple values
I am trying to use the Python itertools.groupby function to change this list:
items = [
{'price': 5.0, 'name': 'Strawberries'},
{'price': 5.0, 'name': 'Strawberries'},
{'price': 5.0, 'name': '...
0
votes
1
answer
34
views
Confusion about python itertools.tee - will iterators generated by itertools.tee affect each other?
Python version: 3.9.7
I saw such an introduction about itertools.tee on the official documentation.
Return n independent iterators from a single iterable.
But i found that iterator generated by ...
0
votes
1
answer
44
views
Grouping files by their file name and get the latest files based on the last modified
I am currently processing a list of files in multiple sub-directories. I have managed to do that, but the problem is that I have multiple files stored in multiple sub-directories with same file name. ...
0
votes
2
answers
36
views
Is there a way to access each individual permutation with itertools.permutations without adding everything to a list?
I am using Python, and I have a list of strings (around 30). I want to find all the possible permutations of them, and I am doing so with itertools.permutations. Basically what I want to do is after I ...
1
vote
0
answers
47
views
How can I see all the combinations of a list without individual items repeating?
I am running a tournament with 16 participants, who will be split into 4 teams of 4 players each.
I intend to map each player name to their average points and then balance teams using average points. ...
0
votes
1
answer
77
views
Convert a list comprehension to functional programming
I have a list of dictionaries
lst = [{'a': (1, 2, 3), 'b': (2, 3)},
{'c': (3, 6), 'd': (4, 8), 'e': (5, 10)},
{'d': (6, 12), 'e': (7, 14)}]
For each key in each dictionary, I want to ...
0
votes
0
answers
66
views
Permutations without cycles
I want to generate all possible permutations of a list, where cyclic permutations (going from left to right) should only occur once.
Here is an example:
Let the list be [A, B, C]. Then I want to have ...
2
votes
4
answers
79
views
How to start Itertools cycle from a particular point in Python?
I have created an itertools cycle for the English alphabet using the code below,
lowercase_letters_cycle = itertools.cycle(string.ascii_lowercase)
If I run a for loop on this iterator object, the ...