Showing posts with label Syntax. Show all posts
Showing posts with label Syntax. Show all posts

Wednesday, February 2, 2022

Code to handle file not found

import sys

try:

    with open('journal.txt', 'a') as f:

        f.write('input')

except IOError as exc:    # Python 2. For Python 3 use OSError

    tb = sys.exc_info()[-1]

    lineno = tb.tb_lineno

    filename = tb.tb_frame.f_code.co_filename

    print('{} at {} line {}.'.format(exc.strerror, filename, lineno))

    sys.exit(exc.errno)

Saturday, June 15, 2019

Convert a python dictionary to comma separated key list and comma separated value list

I have a dictionary as follows:-
dict={'a':'1','b':'2', 'c':'3'}
To convert it into into a comma separated keys string key_string and a comma separated values string val_string I do the following:-
key_list=[]
val_list=[]

 for key,value in dict.iteritems():
     key_list.append(key)
     val_list.append(value)

 key_string = ','.join(key_list)
 val_string = ','.join(val_list)
The result is
 key_string = "a,b,c"
 val_string = "1,2,3" 

Wednesday, February 20, 2019

Dictionary Update values

d = {1: "one", 2: "three"}
d1 = {2: "two"}

# updates the value of key 2
d.update(d1)
print(d)

d1 = {3: "three"}

# adds element with key 3
d.update(d1)
print(d)

O/P:


Sunday, October 28, 2018

Find indices of the max element of the array in a particular axis.

import numpy as np
  
# Working on 2D array
array = np.arange(12).reshape(3, 4)
print("INPUT ARRAY Values: \n", array)
  
# If No axis mentioned, so it works on entire array
print("\nMax element : ", np.argmax(array))
  
# returning Indices of the max element
# as per the indices
print("\nIndices of Max element on column: ", np.argmax(array, axis=0))
print("\nIndices of Max element on row: ", np.argmax(array, axis=1))

Python Code to convert or reshape 2D to 3D matrix array

from numpy import array
# list of data
data = [[11, 22],
[33, 44],
[55, 66]]
# array of data
data = array(data)
print(data.shape)
# reshape
data = data.reshape((data.shape[0], data.shape[1], 1))
print(data.shape)

Output:

(3, 2)
(3, 2, 1)

Saturday, October 27, 2018

python code to convert data frame to multi dimensional array(matrix) and access its columns

import pandas as pd
import os

os.chdir("D:\\DigitRecog\\Kaggle\\all")

Images = pd.read_csv("train.csv")
type(Images)

Images = Images.values
y=Images[:,0]
y.shape[0]

Tuesday, October 23, 2018

Creating Matrix with random values


numpy.random.rand(d0, d1, ..., dn)

d0,d1,d2...dn : The dimensions of the returned array, should all be positive. 
If no argument is given a single Python float is returned.

Example:
>>> np.random.rand(3,2)

array([[ 0.14022471,  0.96360618],  #random
       [ 0.37601032,  0.25528411],  #random
       [ 0.49313049,  0.94909878]]) #random



Monday, October 22, 2018

Max function in Python


np.max is just an alias for np.amax. This function only works on a single input array and finds the value of maximum element in that entire array (returning a scalar). Alternatively, it takes an axisargument and will find the maximum value along an axis of the input array (returning a new array).

>>> a = np.array([[1, 2, 6],
                  [2, 4, 1]])
>>> np.max(a)
6
>>> np.max(a, axis=0) # max of each column
array([2, 4, 6])


np.maximum will take two arrays and compute their element-wise maximum. Arrays should be compatible. Below is an example:

>>> b = np.array([3, 6, 1])
>>> c = np.array([4, 2, 9])
>>> np.maximum(b, c)
array([4, 6, 9])

Sunday, October 21, 2018

For Loop Example

# Program to iterate through a list using indexing

genre = ['popper', 'rocker', 'jazz built']

# iterate over the list using index
for i in range(len(genre)):
print("I like", genre[i])