851 - 900 Flashcards
numpy.random.shuffle()
This function only shuffles the array along the first axis of a multi-dimensional array.
arr = np.arange(10) np.random.shuffle(arr) 👉 [1 7 5 2 9 4 3 6 0 8]
arr = np.arange(9).reshape((3, 3)) np.random.shuffle(arr) arr 👉 array([[3, 4, 5], [6, 7, 8], [0, 1, 2]])
numpy.transpose(a, axes=None)
Reverse or permute the axes of an array and returns the modified array.
x = np.array([[0, 1], [2, 3]]) print(np.transpose(x)) 👉 [[0 2] [1 3]]
my_array = numpy.array([[1,2,3], [4,5,6]]) print(numpy.transpose(my_array)) 👉 [[1 4] [2 5] [3 6]]
numpy.append(arr, values, axis=None)
Append values to the end of an array.
np.append([1, 2, 3], [[4, 5, 6], [7, 8, 9]]) 👉 array([1, 2, 3, ..., 7, 8, 9])
numpy.inner(a, b, /)
Inner product of two arrays. Ordinary inner product of vectors for 1-D arrays.
a = np.array([1,2,3]) b = np.array([0,1,0]) print(np.inner(a, b)) 👉 2
A = numpy.array([0, 1]) B = numpy.array([3, 4]) print(numpy.inner(A, B)) 👉 4
A = numpy.array([2, 1]) B = numpy.array([3, 4]) print(numpy.inner(A, B)) 👉 10
numpy.outer(a, b, out=None)
Compute the outer product of two vectors.
A = numpy.array([2, 3]) B = numpy.array([3, 4]) print(numpy.outer(A, B)) 👉 [[ 6 8] [ 9 12]]
A = numpy.array([0, 1]) B = numpy.array([3, 4]) print numpy.outer(A, B) 👉 [[0 0] [3 4]]
Array Broadcasting
describes how NumPy treats arrays with different shapes during arithmetic operations. Subject to certain constraints, the smaller array is “broadcast” across the larger array so that they have compatible shapes.
if Rows_1 == Rows_2 and Colums_1 == Colums_2: compatible if (Rows_1 == 1 or Colums_1 == 1) and (Rows_2 == 1 or Colums_2 == 1): compatible if (Rows_1 == 1 or Colums_1 == 1) and (Rows_1 == Rows_2 or Colums_1 == Colums_2) compatible x.shape == (2, 3) y.shape == (2, 3) --- compatible y.shape == (2, 1) --- compatible y.shape == (1, 3) --- compatible y.shape == (3, ) --- compatible y.shape == (3, 2) --- NOT_compatible y.shape == (2, ) --- NOT_compatible x.shape == (1, 2, 3, 5, 1, 11, 1, 17) y.shape == (1, 7, 1, 1, 17) --- compatible
numpy.empty(shape, dtype=float, order=’C’, *, like=None)
🎯 shape — int or tuple of int — Shape of the empty array, e.g., (2, 3) or 2.
🎯 order — {‘C’, ‘F’}, optional, default: ‘C’ — Whether to store multi-dimensional data in row-major (C-style) or column-major (Fortran-style) order in memory.
Return a new array of given shape and type, without initializing entries.
np.empty([2, 2]) 👉 array([[ -9.74499359e+001, 6.69583040e-309], [ 2.13182611e-314, 3.06959433e-309]])
np.empty([2, 2], dtype=int) 👉 array([[-1073741821, -1067949133], [ 496041986, 19249760]])
numpy.diag(v, k=0)
Extract a diagonal or construct a diagonal array.
x = array([[0, 1, 2], [3, 4, 5], [6, 7, 8]]) np.diag(x) 👉 array([0, 4, 8]) np.diag(x, k=1) 👉 array([1, 5]) np.diag(x, k=-1) 👉 array([3, 7]) np.diag(np.diag(x)) 👉 array([[0, 0, 0], [0, 4, 0], [0, 0, 8]])
numpy.zeros(shape, dtype=float, order=’C’, *, like=None)
Return a new array of given shape and type, filled with zeros.
np.zeros(5) 👉 array([ 0., 0., 0., 0., 0.])
np.zeros((5,), dtype=int) 👉 array([0, 0, 0, 0, 0])
np.zeros((2, 1)) 👉 array([[ 0.], [ 0.]])
s = (2,2) np.zeros(s) 👉 array([[ 0., 0.], [ 0., 0.]])
numpy.genfromtxt()
Load data from a text file, with missing values handled as specified.
f = StringIO('''text,# of chars hello world,11 numpy,5''') np.genfromtxt(f, dtype='S12,S12', delimiter=',') 👉 array([(b'text', b''), (b'hello world', b'11'), (b'numpy', b'5')], dtype=[('f0', 'S12'), ('f1', 'S12')]) s = StringIO(u"1,1.3,abcde") data = np.genfromtxt(s, dtype=[('myint','i8'),('myfloat','f8'), ('mystring','S5')], delimiter=",") data 👉 array((1, 1.3, b'abcde'), dtype=[('myint', '<i8'), ('myfloat', '<f8'), ('mystring', 'S5')])
numpy.stack(arrays, axis=0, out=None)
Join a sequence of arrays along a new axis.
a = np.array([1, 2, 3]) b = np.array([4, 5, 6]) np.stack((a, b)) 👉 array([[1, 2, 3], [4, 5, 6]])
np.stack((a, b), axis=-1) 👉 array([[1, 4], [2, 5], [3, 6]])
numpy.squeeze(a, axis=None)
Remove axes of length.
x = np.array([[[0], [1], [2]]]) print(np.squeeze(x)) 👉 [0 1 2]
x = np.array([[[0], [1], [2]]]) print(np.squeeze(x, axis=0)) 👉 [[0] [1] [2]]
pyment
🎯 pip install pyment - install
🎯 pyment -h - get the available options
🎯 python setup.py test - run the unit-tests:
docstrings manager (creator/converter)
To run Pyment from the command line the easiest way is to provide a Python file or a folder: ✅ will generate a patch from file pyment example.py ✅ will generate a patch from folder pyment folder/to/python/progs ✅ will overwrite the file pyment -w myfile.py
To run the unit-tests: import os from pyment import PyComment filename = 'test.py' c = PyComment(filename) c.proceed() c.diff_to_file(os.path.basename(filename) + ".patch") for s in c.get_output_docs(): print(s)
min()
function returns the item with the lowest value, or the item with the lowest value in an iterable. If the values are strings, an alphabetically comparison is done.
x = min(5, 10) print(x) 👉 5
# Найти минималное значение сравнив два значения test = [1, 2, 4, 5, 6] for i in test: print(min(3, i)) 👉 1 👉 2 👉 3 👉 3 👉 3
math.Manhattan Distance
The distance between two points measured along axes at right angles. In a plane with p1 at (x1, y1) and p2 at (x2, y2), it is |x1 - x2| + |y1 - y2|. Lm distance.
Distance of { 1, 6 }, { 3, 5 }, { 2, 3 } from { -1, 5 }
👉 sum = (abs(1 - (-1)) + abs(6 - 5)) + (abs(3 - (-1)) + abs(5 - 5)) +
(abs(2 - (-1)) + abs(3 - 5)) = 3 + 4 + 5 = 12
Distance of { 3, 5 }, { 2, 3 } from { 1, 6 }
👉 sum = 12 + 3 + 4 = 19
Distance of { 2, 3 } from { 3, 5 }
👉 sum = 19 + 3 = 22.
def distancesum (x, y, n): sum = 0 for i in range(n): for j in range(i+1,n): sum += (abs(x[i] - x[j]) + abs(y[i] - y[j])) return sum x = [ -1, 1, 3, 2 ] y = [ 5, 6, 5, 3 ] n = len(x) print(distancesum(x, y, n)
What is the difference between programming and scripting?
Programming is used to create complex software, and it is compiled. Scripting assists programming languages and it is interpreted.
git.rmdir
удалить папку.
print(*objects , sep=’’ , end=’\n’ , file=sys.stdout , flush=False)
💡*objects - объекты Python
💡 sep=’’ - строка, разделитель объектов. Значение по умолчанию None
💡 end=’\n’ - строка, которой заканчивается поток. Значение по умолчанию None
💡 file=sys.stdout - объект, реализующий метод wrtite(string). Значение по умолчанию None
💡 flush=False - если True поток будет сброшен в указанный файл file принудительно.
Значение по умолчанию False
выводит объекты в текстовый поток, отделяя их друг от друга sep и заканчивая поток end. sep, end, file и flush, если они заданы, должны быть переданы в качестве аргументов ключевых слов.
print('Hello') 👉 Hello
print('Hello', 'how are you?') 👉 Hello how are you?
print('Hello', 'how are you?', sep='---') 👉 Hello---how are you?
lst = ['Раз', 'Два', 'Три'] for n, line in enumerate(lst, 1): ....if len(lst) == n: ........print(line) ....else: ........print(line, end='=>') 👉 Раз=>Два=>Три
print(11, 12, 13, 14, sep=';') 👉 11;12;13;14
# использование символа новой строки `\n` в переменной line = 'перенос строки при печати\nс помощью символа новой строки' print(line) 👉 перенос строки при печати 👉 с помощью символа новой строки
numpy.busday_count(begindates, enddates, weekmask=’1111100’, holidays=[], busdaycal=None, out=None)
Counts the number of valid days between begindates and enddates, not including the day of enddates. If enddates specifies a date value that is earlier than the corresponding begindates date value, the count will be negative.
# Number of weekdays in January 2011 np.busday_count('2011-01', '2011-02') 👉 21
# Number of weekdays in 2011 np.busday_count('2011', '2012') 👉 260
# Number of Saturdays in 2011 np.busday_count('2011', '2012', weekmask='Sat') 👉 53
os.path.commonprefix()
used to get longest common path prefix in a list of paths. This method returns only common prefix value in the specified list.
paths = ['/home/User/Desktop', '/home/User/Documents', '/home/User/Downloads'] prefix = os.path.commonprefix(paths) print(prefix) 👉 /home/User/D
paths = ['/usr/local/bin', '/usr/bin'] prefix = os.path.commonprefix(paths) print(prefix) 👉 /usr/