Cartesian product of x and y array points into single array of 2D points

A canonical cartesian_product (almost) There are many approaches to this problem with different properties. Some are faster than others, and some are more general-purpose. After a lot of testing and tweaking, I’ve found that the following function, which calculates an n-dimensional cartesian_product, is faster than most others for many inputs. For a pair of approaches … Read more

Split (explode) pandas dataframe string entry to separate rows

UPDATE 3: it makes more sense to use Series.explode() / DataFrame.explode() methods (implemented in Pandas 0.25.0 and extended in Pandas 1.3.0 to support multi-column explode) as is shown in the usage example: for a single column: In [1]: df = pd.DataFrame({‘A’: [[0, 1, 2], ‘foo’, [], [3, 4]], …: ‘B’: 1, …: ‘C’: [[‘a’, ‘b’, … Read more

Pandas conditional creation of a series/dataframe column

If you only have two choices to select from: df[‘color’] = np.where(df[‘Set’]==’Z’, ‘green’, ‘red’) For example, import pandas as pd import numpy as np df = pd.DataFrame({‘Type’:list(‘ABBC’), ‘Set’:list(‘ZZXY’)}) df[‘color’] = np.where(df[‘Set’]==’Z’, ‘green’, ‘red’) print(df) yields Set Type color 0 Z A green 1 Z B green 2 X B red 3 Y C red If … Read more

Plot a function in python

Ok so here is what you want to do import numpy as np import matplotlib.pyplot as plt from mpl_toolkits.mplot3d import Axes3D # for 3d plotting # constants h = 1.34e-34 m = 1.6e-19 a = 2e-9 # define our function (python standard uses lowercase for funcs/vars) def t(e, u): k2 = np.sqrt(2 * m * … Read more

Python Lists and tuples

Problem is you are trying to send a array that is a python list. At first you need to convert it into nampy array. import numpy as np py_list = [439, 301, 481, 194, 208, 415, 147, 502, 333, 86, 544, 353, 229] convert_numpy = np.array(py_list ) sent = sent[np.convert_numpy,:] and for 1st line [439 … Read more

How do I make a function in python which takes a list of integers as an input and outputs smaller lists with only two values?

If you only want groups of two (as opposed to groups of n), then you can hardcode n=2 and use a list comprehension to return a list of lists. This will also create a group of one at the end of the list if the length of the list is odd: some_list = [‘a’,’b’,’c’,’d’,’e’] [some_list[i:i+2] … Read more

value error in python script

I can reproduce your error with: In [230]: np.concatenate([],0) ————————————————————————— ValueError Traceback (most recent call last) <ipython-input-230-2a097486ce12> in <module>() —-> 1 np.concatenate([],0) ValueError: need at least one array to concatenate In [231]: np.concatenate([np.atleast_2d(i) for i in ()],0) ————————————————————————— ValueError Traceback (most recent call last) <ipython-input-231-007f2dd2af1b> in <module>() —-> 1 np.concatenate([np.atleast_2d(i) for i in ()],0) ValueError: … Read more