Python Array – Java2Blog https://java2blog.com A blog on Java, Python and C++ programming languages Sat, 25 Nov 2023 05:58:47 +0000 en-US hourly 1 https://wordpress.org/?v=6.2.9 https://java2blog.com/wp-content/webpc-passthru.php?src=https://java2blog.com/wp-content/uploads/2022/09/cropped-ICON_LOGO_TRANSPARENT-32x32.png&nocache=1 Python Array – Java2Blog https://java2blog.com 32 32 Count Unique Values in NumPy Array https://java2blog.com/count-unique-values-numpy-array/?utm_source=rss&utm_medium=rss&utm_campaign=count-unique-values-numpy-array https://java2blog.com/count-unique-values-numpy-array/#respond Thu, 04 May 2023 13:28:03 +0000 https://java2blog.com/?p=21521 1. Introduction

One of the common tasks Numpy Users may encounter is count unique values in Numpy Array that can help in exploring the distribution of Nummy Array. In this article, we will see different ways to count unique values in Numpy Array.

2. Using np.unique() Method with len() Method

Use np.unique() method with len() method to count unique values in Numpy array.

import numpy as np
## generate a numpy array
array = np.array([1, 2, 3, 3, 4, 5, 5, 6])
result = len(np.unique(array))
print(result)

Running the above code will display the following output on the console:

6

np.unique() method finds unique values in the array and len() function counts number of elements in the array.

3. Using np.unique() method to display unique values

Use np.unique() to display unique values in numpy array.

import numpy as np
## generate a numpy array
array = np.array([1, 2, 3, 3, 4, 5, 5, 6])
result = np.unique(array)
print(result)

Running the above code will display the following output on the console:

[1 2 3 4 5 6]

np.unique() method finds unique values in the array and returns sorted unique values.

4. Use np.unique() Method with return_counts as true

Use np.unique() method with return_counts flag as true to count occurrences of each unique element in Numpy array.

Let’s assume we already have installed a Python library named numpy to work with arrays. In case, we can use pip install numpy to install this if we don’t have it.

To count occurrences of each element in the NumPy array:

  • Use np.array() to create a NumPy array.
  • Use np.unique() to find unique values and their count.
  • Use lambda function to execute an expression (u, c), unique_values, count
  • Use map() function to apply lambda() function to every element of unique_values and count.
  • Use dict() to create a dictionary containing key-value pair where key is unique_value and value is the count.
import numpy as np
## generate a numpy array
array = np.array([1, 2, 3, 3, 4, 5, 5, 6])
unique_values, count = np.unique(array, return_counts=True)
result = dict(map(lambda u, c: (u, c), unique_values, count))
print(result)

Running the above code will display the following output on the console:

{1: 1, 2: 1, 3: 2, 4: 1, 5: 2, 6: 1}

We used np.array() to generate a numpy array, which stored unique and redundant values to identify unique elements.

The function np.unique() used the array and return_counts=True as parameters. It created a new array of unique_elements and stored the count of these elements in the count variable.

The variable result is a Python dictionary created with the method dict() that receives the mapping of a lambda() function.

  • The lambda() function is anonymous and has no name.
  • The map() function is a one-line iterator that applied the lambda() function to each element of unique_values and count.
  • The dict() function created a dictionary result with unique_value as the key and count as the value.

5. Count Specific Values in Numpy Array

To count specific values in Numpy Array, We can use np.count_nonzero() method with condition.

Here is an example to count number of elements that are equal to 3:

array = np.array([1, 2, 3, 3, 4, 5, 5, 6])
count_3 =np.count_nonzero(array==3)
print(count_3)

Running the above code will display the following output on the console:

2

6. Count Unique Rows in 2D Array

To count unique rows in 2D array, use axis=0 option with 2D array.

a = np.array([[1, 0, 0], [1, 0, 0], [2, 3, 4]])
np.unique(a, axis=0)

Output:

array([[1, 0, 0], [2, 3, 4]])

7. Conclusion

In this article, we explored different options for count unique value in Numpy Array. We can apply these options in Practice based on our need.

np.unique() with len() function is useful when we want to count unique value. In case we want to count occurrences of each unique value, np.unique with return_counts option is useful.

]]>
https://java2blog.com/count-unique-values-numpy-array/feed/ 0
Create Array of Arrays in Python https://java2blog.com/create-array-of-arrays-python/?utm_source=rss&utm_medium=rss&utm_campaign=create-array-of-arrays-python https://java2blog.com/create-array-of-arrays-python/#respond Thu, 04 May 2023 13:01:25 +0000 https://java2blog.com/?p=21830 Use numpy.array() Function

To create an array of the arrays in Python:

  • Use the np.array() function to create a numpy.ndarray type array of the arrays.
import numpy as np

array1 = np.array([1,2,3])
array2 = np.array([4,5,6])
array3 = np.array([7,8,9])

array = np.array([array1, array2, array3])
print(array)
[[1 2 3]
 [4 5 6]
 [7 8 9]]

The Python library NumPy scientifically computes advanced numerical work. It is a language extension that adds support for large, multi-dimensional arrays and matrices in the Python language.

The numpy library provides multi-dimensional array objects that work like arrays in C but with a Python interface. It can therefore act as a bridge between Python and the low-level languages used for scientific computing.

We used the np.array() function to create three arrays: array1, array2, and array3. After we finished generating the arrays, we used the np.array() function to create an arrays of them.

The np.array() function is a general-purpose tool for creating and manipulating arrays in the Python programming language. It converts any iterable object to an array of the same type.

It is not a function in the same sense as len() or str() is, but a factory function or class. The constructor can take any number of arguments. For example, we used the np.array() function to create a numpy.ndarray type array of array1, array2, and array3.

Manually create array of arrays

You can directly create array of arrays by specifying array elements to np.array() method.

Here is an example:

import numpy as np
array = np.array([[1,2,3],
                 [4,5,6],
                 [7,8,9]])
print(array)
[[1 2 3]
 [4 5 6]
 [7 8 9]]

Here, we directly passed 2d array to np.array() method to create array of arrays in Python.

Use numpy.append() Function

To generate an array of the array(s) in Python:

  • Use the np.append() function that appends arrays to generate a numpy.ndarray type array.
import numpy as np

array1 = np.array([1,2,3])
array2 = np.array([4,5,6])
array3 = np.array([7,8,9])

array = np.append(arr=[array1], values=[array2, array3], axis=0)
print(array)
[[1 2 3]
 [4 5 6]
 [7 8 9]]

We already discussed the numpy library and np.array() function while explaining the code snippet for creating an array of arrays using the numpy.array() function.

The np.append() is a built-in function in the numpy library that adds one iterable object to another in Python. It takes arguments as:

  • The arr to add an iterable at its end.
  • The values to add at the end of arr.
  • The axis to append the values along. By default, it flattens the arr and the values.

We used the np.append() function to append array2 and array3 to the end of array1. In addition, we defined axis=0 to make a multi-dimensional array from the arrays instead of flattening them.

]]>
https://java2blog.com/create-array-of-arrays-python/feed/ 0
Create Empty Array in Python https://java2blog.com/create-empty-array-python/?utm_source=rss&utm_medium=rss&utm_campaign=create-empty-array-python https://java2blog.com/create-empty-array-python/#respond Sun, 12 Mar 2023 19:18:39 +0000 https://java2blog.com/?p=22835 Creating an Empty Array in Python

Before moving towards various solutions for creating an empty array in Python, we must understand what an empty array means. It means a collection of items with a particular data type containing no items or elements. We can use different ways to create an empty one-dimensional, two-dimensional and multi-dimensional array in Python. Let’s learn each of them one by one.

Use the numpy Library to Create an Empty Array

Use the numpy library to create an empty one-dimensional array in Python.

import numpy as np
array = np.array([])

if array.size == 0:
    print("Array is empty")
else:
    print("Array is not empty")
Array is empty

First, we imported the numpy library, an essential Python module for working with arrays. Then, we used the as keyword to set np as an alias for the numpy library. This way, we don’t have to type numpy again and again; instead, we can use np.

The numpy module performs various mathematical operations on arrays in Python. By using numpy, we can add a powerful data structure which ensures efficient calculations with matrices and arrays; it provides an enormous library of complex mathematical functions that operate on these matrices and arrays in Python.

The np.array() method creates an array with the provided sequence. We used this method to create an empty array. Here, [] denotes an empty list, creating an empty numpy array. This particular array will have the shape of (0,) and data type float64; you can check the shape and data type by using the following code.

print(array.shape)
print(array.dtype)
(0,)
float64

You might be thinking about how the data type is decided to be float64 when an array is empty. Remember, the array’s data type is determined based on the elements of the array; if the array is empty, then its data type is set to float64 by default.

Finally, we used the if-else block with array.size to check whether the size of the array is equal to 0 or not. If it is, print Array is empty; otherwise, display Array is not empty. Note that array.size will return True if the array is empty; else, False.

Use the numpy library to create an empty two-dimensional array in Python.

import numpy as np
array = np.empty((0,0))

if array.size == 0:
    print("Array is empty")
else:
    print("Array is not empty")
Array is empty

This code is similar to the previous code example, but we used the np.empty() method to create a two-dimensional empty array in Python. This method returned a new array of the specified shape, data type and without initializing the entries. In our case, the shape is (0,0) representing 0 rows and 0 columns while the data type is float64, which is set by default as we did not specify any data type.

If we want to create an empty 2-D array of int32 data type, we must set the dtype to int as follows.

import numpy as np
array = np.empty((0,0), dtype=int)

if array.size == 0:
    print("Array is empty")
else:
    print("Array is not empty")

print(array.shape)
print(array.dtype)
Array is empty
(0, 0)
int32

Use the numpy library to create an empty multi-dimensional array in Python.

import numpy as np
array = np.empty((3,4,4))

if array.size == 0:
    print("Array is empty")
else:
    print("Array is not empty")
Array is not empty

This example created an array with the shape of (3,4,4) with the default data type (float64) and uninitialized data, which means the items in the array would be some random and meaningless values; this is the reason, the above code resulted in Array is not empty. You can replace the np.empty() with the np.zeros() function to create an array of a particular shape with all items set to 0.

It does not matter if you replace np.empty() with the np.zeros() method; the array will not be empty because 0 is also a value. This method is useful when you want an array containing a specific shape with all elements set to a particular number.

Use List Comprehension to Create an Empty Array

Use list comprehension to create an empty one-dimensional array in Python.

import numpy as np
array = [None] * 0

if len(array) == 0:
    print("Array is empty")
else:
    print("Array is not empty")
Array is empty

We used list comprehension (a shorter syntax) for this code to create an empty array. We used [None] * 0 to create an empty array; how? The * was used to repeat an element a given number of times. We repeated the None element 0 times in the above code to create an empty array. Here, the array would be of list type.

Next, we used the if-else block to determine if the specified array is empty; for that, we checked the size of the array using the len() function. This function returns the number of elements. So, we used the comparison operator (==) to check if the returned number of elements is equal to 0 or not. If it is equal to zero, the expression len(array) == 0 will result in a True and if block will be executed; otherwise, the else block will be executed.

Use list comprehension to create an empty two-dimensional array in Python.

import numpy as np
array = [[0 for i in range(0)] for j in range(0)]

if len(array) == 0:
    print("Array is empty")
else:
    print("Array is not empty")
Array is empty

Here, we used list comprehension to create a 2-D array in Python. Usually, learners find it hard to understand but believe me, it is easy to understand. First, the outer list comprehension (represented with [... for j in range(0)]) created a list of sub-lists, whereas the inner list comprehension created every sub-list (represented with [0 for i in range(0)]).

Here, the range(0) method returned an empty range, which let the inner list comprehension create an empty array. Finally, the outer list comprehension created a 2-D list with no elements, essentially considered an empty 2-D array.

Use list comprehension to create an empty multi-dimensional array in Python.

import numpy as np
array = [[[0 for i in range(0)] for j in range(0)] for k in range(0)]

if len(array) == 0:
    print("Array is empty")
else:
    print("Array is not empty")
Array is empty

This example is the same as we practised earlier than this. The only difference is that we create a multi-dimensional array by adding one more for in a list comprehension.

The number of dimensions = the number of for in a list comprehension

Use the array Module to Create an Empty Array

Use the array module to create an empty one-dimensional array in Python.

import array
array = array.array("i", [])

if len(array) == 0:
    print("Array is empty")
else:
    print("Array is not empty")
Array is empty

Here, we used the .array() method of the array module to create an empty array. The array module efficiently works with arrays having numeric values. The .array() method has two arguments: a typecode and an empty list.

The typecode represents the data type of the array’s items. In our case, it is i, which means integer type. The second argument represented with [] is an empty list which specifies the array will be empty.

Next, we used the if-else block to print if the array is empty or not based on the specified condition. If you are curious about how this condition worked? [Scroll back](add link using the id or name attribute of this paragraph) to learn.

Use the array module to create an empty two-dimensional array in Python.

import numpy as np
array = [array.array("i", []) for i in range(0)]

if len(array) == 0:
    print("Array is empty")
else:
    print("Array is not empty")
Array is empty

Here, we used the .array() method with a list comprehension. In [array.array("i", []) for i in range(0)] expression, the .array() method created an empty array with typecode i and for loop specified that the list comprehension must hold no elements.

Use the array module to create an empty multi-dimensional array in Python.

import numpy as np
array = [[array.array("i", []) for j in range(0)] for i in range(0)]

if len(array) == 0:
    print("Array is empty")
else:
    print("Array is not empty")
Array is empty

This example code is similar to the previous one, but we added an extra for to create an empty multi-dimensional array.

That’s all about how to create empty array in Python.

]]>
https://java2blog.com/create-empty-array-python/feed/ 0
Create Array of All NaN Values in Python https://java2blog.com/create-array-of-all-nan-values-python/?utm_source=rss&utm_medium=rss&utm_campaign=create-array-of-all-nan-values-python https://java2blog.com/create-array-of-all-nan-values-python/#respond Tue, 27 Dec 2022 08:33:40 +0000 https://java2blog.com/?p=21983 Using numpy.empty() Function

To create an array of all NaN values in Python:

  • Use numpy.empty() to get an array of the given shape.
  • Assign numpy.nan to every array element using the assignment operator (=).
import numpy
array = numpy.empty((3,3))
array[:] = numpy.nan
print(array)
[[nan nan nan]
 [nan nan nan]
 [nan nan nan]]

We used numpy.empty() to get an array of the given shape and dtype. Here, shape means the number of rows and columns (we used 3 by 3), and dtype means the data type of the returned/output array; by default, it is numpy.float64.

Next, we used the assignment operator (=) to assign nan to all the array entries. We could also use the ndarray.fill() method to fill all the entries with nan as follows:

import numpy

array=numpy.empty((3,3)) 
array.fill(numpy.NaN)  
print(array)
[[nan nan nan]
 [nan nan nan]
 [nan nan nan]]

Using numpy.full() Function

To create an array of all nan values in Python, use the numpy.full() function to get an array of the specified shape (rows and columns) and fill value.

import numpy

array = numpy.full((3,3),numpy.nan)
print(array)
[[nan nan nan]
 [nan nan nan]
 [nan nan nan]]

To work with arrays, we must have numpy installed on our machine. We can install it using the pip command as pip install numpy on Windows operating system if it is not installed yet. You can check this article to install numpy on MacBook.

We used the numpy.full() function to get an array of the given shape (rows and columns) and fill value. This function took the following two parameters:

  1. shape – We used it to specify the number of rows and columns. Here, we created a matrix of 3 by 3.
  2. fill_value – It denotes the fill value, which was used to fill the array slots. We filled the array with nan.

The numpy.full() function can also take the dtype, order, and like parameters. Here, the dtype is an optional parameter and denotes the data type of the required array.

The order parameter is also optional and denotes F_contiguous or C_contiguous order; these are the orders in which we can store multidimensional data.

Like dtype and order, the like parameter is optional too; it represents the array_like object or prototype.

Using numpy.tile() Function

To create an array of all nan values in Python:

  • Use numpy.array() to create a 0-dimensional array with the given value.
  • Use the numpy.tile() function to get an array of the specified shape (rows and columns) and fill value.
import numpy
input_array = numpy.array(numpy.nan)
array = numpy.tile(input_array,(3,3))
print(array)
[[nan nan nan]
 [nan nan nan]
 [nan nan nan]]

After importing the numpy module, we used numpy.array() to create a 0-D (0 dimensional) array with value nan. Note that using this function, we can create an array of 1, 2, 3, 4, 5, or any dimensions.

Next, we used the numpy.tile() function to create an array of all nan values in Python. This function took two parameters, A (input array) and reps (number of repetitions of A along every axis).

The numpy.tile() function took an array as an input and returned an array repeated by the specified number of repetitions. How? For instance, if we pass a tuple (1,2), the numpy module will tile the original array once along the first and twice along the second dimensions.

Remember that we can pass an array or array-like data structure to the parameter A. On the other hand, the reps parameter is a bit challenging because it can modify the array’s dimensions and define the shape in which we want to tile our array.

Using numpy.repeat() Function

To create an array of all nan values in Python:

  • Use np.array() with * operator to create two dimensional array.
  • Use the numpy.repeat() function to repeat the individual elements of the array according to the given number of repetitions.
import numpy
input_array = np.array([[np.nan]]*3)
array=numpy.repeat(input_array,3,axis=1)
print(array)
[[nan nan nan]
 [nan nan nan]
 [nan nan nan]]

First, we used numpy.array() with the * operator to have a 2-D array. Next, we used the numpy module’s repeat() function to repeat the individual elements of the array. This function took the following three parameters:

  • array – Denotes the input array (array-like).
  • repeat – Represents the required number of repetitions of every array element along a given axis.
  • axis – Denotes the axis along which we will repeat values. By default, it returns a flat array as an output. For a 1-D array, we have only one axis, which is axis 0, but for 2-D arrays, we have two axes, axis 1 on the x-axis and axis 0 on the y-axis.

In our code example, we repeated the nan thrice on the x-axis because we had set the value of the axis to 1.

Using Multiplication of numpy.ones() with nan

To create an array of all nan values in Python:

  • Use the numpy.ones() function to get an array of the given shape (the number of rows and columns).
  • Use the * operator to replace the default value of the array produced by the numpy.ones() function (used in the previous step) with the numpy.nan value.
import numpy
array=numpy.ones((3,3))* numpy.nan
print(array)
[[nan nan nan]
 [nan nan nan]
 [nan nan nan]]

Here, we used the numpy.ones() function to create a multidimensional array by specifying the shape parameter. Then, we used this function to get an array of the given shape, 3 by 3. Note that the array returned by numpy.ones() was filled with 1 by default.

So, we used the * operator to multiply every element with numpy.nan to update from 1 to nan. Finally, we used the print() function to print the resultant array.

Remember, the numpy.ones() function is similar to the numpy.zeros(). We can also pass dtype, order, and like parameters, which are the same as we learned while using the numpy.full() function.

That’s all about how to create array of all NaN values in Python

]]>
https://java2blog.com/create-array-of-all-nan-values-python/feed/ 0
Convert String Array to Int Array in Python https://java2blog.com/convert-string-array-to-int-array-python/?utm_source=rss&utm_medium=rss&utm_campaign=convert-string-array-to-int-array-python https://java2blog.com/convert-string-array-to-int-array-python/#respond Sun, 25 Dec 2022 07:17:04 +0000 https://java2blog.com/?p=21841 This tutorial will demonstrate how to convert string array to int array in Python.

Using the for loop with int() function

To convert string array to int array in Python:

  • Use the for loop to loop through the array.
  • Use the int() function to convert each element to an integer in every iteration.

See the code below.

lst = ['2','4','6','11']
lst_int = []
for i in lst:
    lst_int.append(int(i))
print(lst_int)

Output:

[2, 4, 6, 11]

In the above example, we iterated over a list and converted each element individually to an integer using the int() function. Each element was appended to an empty list using the append() function.

We can perform the above operation more efficiently by using the list comprehension technique. This method is used to create a list using a for loop in a single line of code.

For example,

lst = ['2','4','6','11']
lst_int = [int(i) for i in lst]
print(lst_int)

Output:

[2, 4, 6, 11]

Using for loop with eval() function

Use the eval() function to convert string array to int array in Python

lst = ['2','4','6','11']
lst_int = [eval(i) for i in lst]
print(lst_int)

Output:

[2, 4, 6, 11]

The eval() function accepts a Python string and evaluates it as a Python expression. We can use it in place of the int() function in the previous method.

Using the map() with list() function

To convert string array to in array in Python:

  • Use the map() function to apply the int() function to all elements of the array.
  • Use the list() function to convert the map type object to a list.
lst = ['2','4','6','11']
lst_int = list(map(int,lst))
print(lst_int)

Output:

[2, 4, 6, 11]

The map() function can be used to apply the int() function to all the elements of the array. In Python 3, the map() function returns a map type object which can be converted to a list. In Python 2, this function directly returns a list.

Conclusion

To conclude, we discussed several methods to convert string array to int array in Python.

In the first method, we used a for loop to iterate over the array and convert each element to an integer using the int() function. This can be achieved efficiently using the list comprehension technique.

In the second method, we replaced the int() function with the eval() function. In the final method, we discussed the use of the map() function to apply the int() function to every element of the array.

That’s all about how to convert String array to int array in Python.

]]>
https://java2blog.com/convert-string-array-to-int-array-python/feed/ 0
Fill Array with Random Numbers in Python https://java2blog.com/fill-array-with-random-numbers-python/?utm_source=rss&utm_medium=rss&utm_campaign=fill-array-with-random-numbers-python https://java2blog.com/fill-array-with-random-numbers-python/#respond Mon, 27 Jun 2022 13:12:21 +0000 https://java2blog.com/?p=20366 Fill array with random numbers in Python

An array is one of the fundamental data structures in Python. It stores elements in a contiguous memory location and each element can be accessed using its respective index. In Python, the numpy library is used to implement array data structures. Lists are also another data structure that mimics an array in Python.

In this tutorial, we will discuss different methods to fill array with random numbers in Python.

We can create an array of our desired shapes. Sometimes, we may require dummy arrays for some calculations. We can create an array filled with such dummy values since the numpy library also implements a random module to generate random numbers.

Ways to fill array with random numbers in Python

Let us now discuss how to fill array with random numbers in Python.

Using the numpy.random.randint() function to fill array with random numbers in Python

As discussed earlier, the numpy library has a random module that can help in generating random numbers for numpy arrays. The randint() function can be used to generate an array of the required size and fill array with random numbers in Python.

We need to remember the three main parameters. The first two parameters are the low and high values. The function will select a random integer between this range. The third parameter is the shape parameter which specifies the shape of the final array.

See the following example.

import numpy as np
arr = np.random.randint(0,10,10)
print(arr)

Output:

[3 8 1 0 4 2 4 7 0 3]

In the above example, we generate random numbers between 0 to 10 and fill it in a one-dimensional array of length ten.

Using the numpy.random.Generator.integers() function to fill array with random numbers in Python

The numpy.random.Generators offer a new way to generate and work with random numbers. It uses an additional BitGenerator to spawn such random bits and manage their states. To initiate a new Generator, we use the numpy.random.default_rng() constructor.

After this, we can use the numpy.random.Generator.integers() function to generate random numbers and fill array with random numbers in Python.

We need to specify the low, high, and shape values in this function as we did in the previous method.

For example,

import numpy as np
g = np.random.default_rng()
arr = g.integers(0,5,10)
print(arr)

Output:

[0 2 1 1 1 0 1 1 3 0]

Using the random.randint() function to fill array with random numbers in Python

As discussed in the first section, lists in Python also mimic an array. We can fill lists with random numbers using the random module in Python. We will use list comprehension along with the random.randint() function to fill array with random numbers in Python.

We will use the random.randint() function to generate a random number between a given range. We will use the list comprehension method that loops over this function the required number of times, creating a new list of the required length.

See the following code.

import random
arr = [random.randint(1,5) for _ in range(10)]
print(arr)

Output:

[4, 2, 5, 3, 2, 2, 3, 3, 4, 2]

Conclusion

To conclude, in this tutorial we discussed different methods to fill array with random numbers in Python. Essentially, we were creating arrays with random numbers. For this, we used numpy arrays and lists.

For numpy arrays, we had two methods. The first was the traditional numpy.random.randint() function that generates a numpy array of a given length filled with random numbers between a given range.

In the second method, we used a relatively new numpy.random.Generators module to create the array. It uses Generators that provide an additional state to manage and generate random bits.

In the final method, we discussed how to fill array with random numbers in Python using the list comprehension method and the random.randint() function. Essentially, we create a loop and run the randint() function the required number of times and add the generated number to a list.

]]>
https://java2blog.com/fill-array-with-random-numbers-python/feed/ 0
Add Month to datetime in Python https://java2blog.com/add-month-to-datetime-python/?utm_source=rss&utm_medium=rss&utm_campaign=add-month-to-datetime-python https://java2blog.com/add-month-to-datetime-python/#respond Tue, 17 May 2022 15:43:38 +0000 https://java2blog.com/?p=19841 In Python, we can represent date values using the standard datetime library. We can store all the attributes of the date along with time attributes in datetime objects. The datetime objects can be manipulated with other libraries also like dateutil, pandas, and more.

We cannot directly add or subtract datetime objects and use the datetime.timedelta object to represent such intervals of time for an addition. However, this object cannot represent intervals of months, so we need to look for alternative methods.

Ways to add month to datetime in Python

Different methods on how to add months to datetime in Python are discussed below.

Using the datetime.datetime constructor to add month to datetime in Python.

The datetime.datetime constructor is used to initializing datetime objects in Python. This constructor accepts the month and other attributes for the date and time values.

We cannot directly overwrite such objects. We can just initialize the values at first and access them.

However, we can create our own function to create a new datetime object with updated values. We will use the values from the defined object and perform some calculations to create a new object.

See the code below.

from datetime import datetime
def add_mon(d,x):
    dom = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]
    n_month = ((( d.month - 1) + x ) % 12 ) + 1
    newyear  = d.year + ((( d.month - 1) + x ) // 12 ) 
    if d.day > dom[n_month-1]:
        n_day = dom[n_month-1]
    else:
        n_day = d.day
    return datetime( newyear, n_month, n_day)
d = datetime(2022,6,10,16,20,15)
d_new = add_mon(d, 2)
print(d_new)

Output:

2022-08-10 00:00:00

In the above example, the add_mon() function creates a new datetime object after adding the months to a give datetime object.

Using the dateutil.relativedelta object to add month to datetime in Python

The dateutil module was developed to increase the functionalities of the standard datetime module. We can use functions from this module to work with datetime objects.

This module provides a relativedelta object to represent intervals of time, similar to the timedelta object of the datetime module. The difference between the two is that the former accepts a wide range of attributes (including months) and the latter has very few attributes.

Due to this, the relativedelta object can represent different intervals of time. We can use it to add months to datetime in Python.

For example,

from datetime import datetime
from dateutil.relativedelta import relativedelta
d = datetime(2022,6,10,16,20,15) + relativedelta(months = 2)
print(d)

Output:

2022-08-10 16:20:15

Using the pandas.DateOffset() function to add month to datetime in Python

The pandas library is used to work with DataFrame objects in Python. Columns of DataFrame can contain timestamp values that represent date and time values.

Due to this, the pandas library also has some basic functionalities for working with such values. We can use the pandas.DateOffset() function to add months to datetime in Python.

This function is used to create time intervals. With the months attribute, we can create intervals of months and add them to any given datetime object.

See the code below.

from datetime import datetime
import pandas as pd
d1 = datetime(2022,5,8,15,20,15)
d2 = d1 + pd.DateOffset(months = 2)
print(d2)

Output:

2022-07-08 15:20:15

In the above example, we adds an interval of 2 months using the pandas.DateOffset() function.

Using the arrow.shift() function to add month to datetime in Python

arrow was introduced as a third-party package that combines the functionalities of datetime and dateutil into one and provides easy-to-use functionalities.

This module has its own objects that can be used to represent date and time values. The shift() function can be used to update such objects by adding or subtracting intervals of time. We can use the months attribute in this function to add months to the object.

For example,

import arrow
t = arrow.now()
new_t = t.shift(months=2)
print(new_t)

Output:

2022-07-09T03:44:35.343283+05:30

Conclusion

In this tutorial, we discussed several methods to add months to datetime in Python. The datetime object cannot be overwritten but we can use the values from this object to create a new object after adding the months. The timedelta object will not work in this case. The relativedelta object from the dateutil module can be used to add months to datetime in Python. Similarly, we can use the pandas.DateOffset() function as well. The arrow module is also discussed since it has a direct function to update its object and add months to it.

]]>
https://java2blog.com/add-month-to-datetime-python/feed/ 0
Create an Array of 1 to 10 in Python https://java2blog.com/create-array-of-1-to-10-python/?utm_source=rss&utm_medium=rss&utm_campaign=create-array-of-1-to-10-python https://java2blog.com/create-array-of-1-to-10-python/#respond Tue, 03 May 2022 09:41:18 +0000 https://java2blog.com/?p=19820 In this article, we will see how to create an array of 1 to 10 in Python.

Introduction

Arrays are an essential part of any programming language and are widely used by programmers in every field of coding. Python seems to have a different approach related to the use of arrays, as it does not directly support the use of arrays. However, in Python, we make use of either Lists or an array indirectly from the NumPy library. This tutorial demonstrates the different ways available to create an array of 1 to 10 in Python.

Before we move on, let us understand what the basic terminologies involved in this article are.

What is a list in Python?

As you now know, there is no direct support available for arrays in Python. Lists are perfectly capable of acting as one-dimensional arrays, or for that matter, a list of lists can act as a multi-dimensional array, but there is always a limit to the number of dimensions in this method. Lists are capable of storing a number of items in one single variable, a quality that is similar to arrays.

What are NumPy arrays in Python?

There is yet another indirect way to deal with arrays in Python, and that is to import the NumPy library and utilize its functions. If dealing with multi-dimensional arrays, NumPy arrays tend to be a better option than generic lists as they use a lot less memory and are more convenient in terms of the readability of the code.

How to create an array of 1 to 10 in Python?

Using the range() function to create an array of 1 to 10 in Python.

The range() function, as its name suggests is predominantly utilized to provide the range between which a sequence of numbers needs to be returned, this range being the arguments of this function. If not specified, the starting point of the range function defaults to 0.

The range() function’s syntax has been explained below for ease of understanding.

range(start, stop, step)

The range() function has the following parameters.

  • start: It specifies the point of the beginning of the range that is to be specified. It defaults to 0.
  • stop: It specifies the point of the end of the range that is to be specified. This parameter is exclusive in the range.
  • step: An optional parameter, it indicates the step value that specifies the amount to be incremented. It defaults to 1.

The following code uses the range() function to create an array of 1 to 10 in Python 2.x versions.

# Python 2 code
x = range(1,11)
print x

The above code provides the following output:

[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

In the versions Python 2.x, we only need to directly utilize the range() function to create a list with the specified values.

However, in the versions released after Python 3, we also need to utilize the list() function along with the range() function to successfully create the specified list.

The following code uses the range() function to create an array of 1 to 10 in Python 3.x versions.

# Python 3 code
x = list(range(1,11))
print (x)

The above code provides the following code:

[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

We should note that the stop parameter is exclusive in the range() function, which means that it is not included in the list of the specified numbers. Here, we needed to create an array from 1 to 10, therefore, we have specified the stop parameter in the range() function as 11.

Using list comprehension along with the range() function to create an array of 1 to 10 in Python.

List comprehension is a concise way of creating lists as it reduces the lines of code needed to create a list. The range() function, when combined with list comprehension is capable of achieving the same result as using the list() function, but in a more easy-to-understand way.

The following code uses list comprehension along with the range() function to create an array of 1 to 10 in Python.

a = [x for x in range(1,11)]
print(a)

The above code provides the following output:

[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

Using a user-defined function to create an array of 1 to 10 in Python.

We can simply create a user-defined function with the help of the for loop that manually increments each value and appends it to a given list.

The following code uses a user-defined function to create an array of 1 to 10 in Python.

def UDlist(n):
    x = []
    for a in range(n+1):
      x.append(a)
    return(x)
print(UDlist(10))

The above code provides the following output:

[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

Using the NumPy.arange() function to create an array of 1 to 10 in Python.

Till now, we have been taking a look at functions that create a list. This method, however, deals with the creation of NumPy arrays.

The term NumPy is an acronym for Numerical Python and is a Python library that makes it possible to deal with arrays and matrices in Python. We can utilize the arange() function from the NumPy library to create an array with the desired specifications.

The following code uses the NumPy.arange() function to create an array of 1 to 10 in Python.

import numpy as np
x = np.arange(1,11)
print(x)

The above code provides the following output:

[ 1 2 3 4 5 6 7 8 9 10]

Conclusion

The article was focused on and provided the different ways available to create an array of 1 to 10 in Python. The article provides the different ways by which an array can be indirectly created and utilized in a way that is supported in Python. The article covers four ways in total. Out of these four, the first three ways are utilized to create a list that acts as an alternative to a simple array, while the fourth way creates an array using the popular NumPy library.

]]>
https://java2blog.com/create-array-of-1-to-10-python/feed/ 0
How to Append to Array in Python https://java2blog.com/python-append-to-array/?utm_source=rss&utm_medium=rss&utm_campaign=python-append-to-array https://java2blog.com/python-append-to-array/#respond Thu, 30 Dec 2021 05:54:28 +0000 https://java2blog.com/?p=18615 In python, we have three implementations of the array data structure. In this article, we will discuss those array implementations. After that, see how we can append elements to the different array implementations in python. 

What are the Different Array Implementations in Python?

We can implement arrays using three different approaches namely lists, array module, and NumPy module in python. Let us discuss them one by one.

Python Lists

Python lists are the most generic implementation of array data structure in python. We can store objects with different data types in a single list. To create a list with given elements, we can use the list() constructor. The list() constructor accepts a collection of elements as input argument and returns a list object with all the given elements as shown in the following example.

myList = list((1, 2, 3, 4, 5, 6, 7, 8, 9, 10))
print("The list is:", myList)

Output:

The list is: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

Here, we have provided a tuple containing 10 numbers as an input argument to the list() constructor. After execution, it has returned a list object that is assigned to the myList variable.

Instead of using the list() constructor, you can use the square brackets [ ] to create a list using the given elements if you have individual elements instead of a collection object. You can observe this in the following example.

myList = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
print("The list is:", myList)

Output:

The list is: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

Here, we have created a list using the square brackets and individual elements instead of a collection object.

We can also create a list using the elements of other container objects such as a set or a tuple. For this, we just need to pass the container object to the list() constructor as follows.

mySet = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10}
print("The set is:", mySet)
myList = list(mySet)
print("The list is:", myList)

Output:

The set is: {1, 2, 3, 4, 5, 6, 7, 8, 9, 10}
The list is: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

In the above example, we have created a list using the elements of a set by giving the set object as an input argument to the list() constructor.

Lists are container objects and they can also contain other container objects along with other elements as shown below.

mySet = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10}
print("The set is:", mySet)
myList = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, mySet]
print("The list is:", myList)

Output:

The set is: {1, 2, 3, 4, 5, 6, 7, 8, 9, 10}
The list is: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, {1, 2, 3, 4, 5, 6, 7, 8, 9, 10}]

Here, we have created a list that contains a set within it. Hence, a list can also contain other container objects.

Python Arrays

You can see that there are no restrictions on the data types of the elements in a list. However, python provides us with the arrays module to create arrays with a specific data type. You can install the arrays module using PIP as follows.

pip install arrays

In python3, you can download the arrays module as follows.

pip3 install arrays

To create an array using the arrays module, we use the array() constructor. The array() constructor takes a character denoting the data type of the elements of the array and the elements of the array in a list as the second input argument. For character codes for the different data types, you can refer to the official documentation for the arrays module.  Upon execution, it returns an array with the elements of the specified data types as follows.

import array

myArr = array.array("i", [1, 2, 3, 4, 5, 6, 7, 8, 9, 10])
print("The array is:", myArr)

Output:

The array is: array('i', [1, 2, 3, 4, 5, 6, 7, 8, 9, 10])

Here, we have specified the first input argument as “i” to denote that the elements in the array are signed integers. Similarly, we can specify “f” for floating-point values, “d” for double values, “b” for signed characters, etc. After execution, the array() function returns an array object.

If the input list in the second input argument to the array() constructor contains elements with the data types other than that specified in the first input argument, it raises the TypeError exception as follows.

import array

myArr = array.array("i", [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, "java2blog"])
print("The array is:", myArr)

Output:

Traceback (most recent call last):
  File "/home/aditya1117/PycharmProjects/pythonProject/string1.py", line 3, in <module>
    myArr = array.array("i", [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, "java2blog"])
TypeError: an integer is required (got type str)

Here, when we tried to include a string in an integer array, the program ran into TypeError exception and showed the message “TypeError: an integer is required (got type str)

Also, we cannot add other container objects to the arrays in python.

import array

mySet = {1, 2, 4}
myArr = array.array("i", [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, mySet])
print("The array is:", myArr)

Output:

Traceback (most recent call last):
  File "/home/aditya1117/PycharmProjects/pythonProject/string1.py", line 4, in <module>
    myArr = array.array("i", [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, mySet])
TypeError: an integer is required (got type set)

Here, we have tried to insert a set in an integer array. Again, the program runs into the TypeError exception and shows the message “TypeError: an integer is required (got type set)

Python Numpy Arrays

NumPy arrays are multidimensional arrays. We can also use NumPy arrays as one-dimensional arrays by defining 2-dimensional arrays of shape Nx1 where N is the number of columns i.e. elements in the 1-D array and 1 denotes that the multidimensional array has only one row. 

To create a NumPy array, we can use the array() constructor. The array() constructor takes a collection of elements as its first argument and returns an object of type ndarray as follows.

import numpy

myArr = numpy.array([1, 2, 3, 4, 5, 6, 7, 8, 9, 10])
print("The array is:", myArr)
print("Type of array is:", type(myArr))

Output:

The array is: [ 1  2  3  4  5  6  7  8  9 10]
Type of array is: <class 'numpy.ndarray'>

Here, you can observe that we have created an array of type numpy.ndarray with 10 elements. You can also observe that we have simply passed a list to the array() function and haven’t specified the data type for the elements.

If we do not specify the data type of elements in the NumPy array, we can create an array of elements of different data types as follows.

import numpy

myArr = numpy.array([1, 2, 3, 4, 5, 6, 7, 8, 9, "java2blog"])
print("The array is:", myArr)
print("Type of array is:", type(myArr))

Output:

The array is: ['1' '2' '3' '4' '5' '6' '7' '8' '9' 'java2blog']
Type of array is: <class 'numpy.ndarray'>

Here, we have created a NumPy array with integers and strings as its elements.

You can also specify the data type of the elements explicitly using the “dtype” parameter. The default value for the “dtype” parameter is “None”. When we don’t specify the data type of the elements of the array to be created, the array() function automatically recognizes the datatype of the elements in the input. Otherwise, we can specify the data type of the elements as follows.

import numpy

myArr = numpy.array([1, 2, 3, 4, 5, 6, 7, 8, 9], dtype="i")
print("The array is:", myArr)
print("Type of array is:", type(myArr))

Output:

The array is: [1 2 3 4 5 6 7 8 9]
Type of array is: <class 'numpy.ndarray'>

Here, we have specified the data type of the elements as integer data type by providing the argument "i” to the dtype parameter.

Here, you have to make sure that the elements of the collection object are of the same data type or at least compatible data types like int and float. In the case of incompatible data types, the array() constructor raises the ValueError exception as follows.

import numpy

myArr = numpy.array([1, 2, 3, 4, 5, 6, 7, 8, 9, "java2blog"], dtype="i")
print("The array is:", myArr)
print("Type of array is:", type(myArr))

Output:

Traceback (most recent call last):
  File "/home/aditya1117/PycharmProjects/pythonProject/string1.py", line 3, in <module>
    myArr = numpy.array([1, 2, 3, 4, 5, 6, 7, 8, 9, "java2blog"], dtype="i")
ValueError: invalid literal for int() with base 10: 'java2blog'

In the above example, we have specified the data type of the elements of the array to be the integer type. However, the list that has been passed to the array() function contains a string in it. Hence, the program runs into the ValueError exception showing the message ValueError: invalid literal for int() with base 10: 'java2blog'.

Having discussed the implementation of different types of arrays in python, let us discuss how we can append elements to an array in python.

Append Element to List in python

You can append elements to a list in python using the append() method. The append() method, when invoked on a list, takes the element to be appended as the input argument and appends the element at the end of the list as shown below.

myList = [1, 2, 3, 4, 5, 6, 7, 8, 9]
print("The original list is:", myList)
myList.append(10)
print("The list after append operation is:", myList)

Output:

The original list is: [1, 2, 3, 4, 5, 6, 7, 8, 9]
The list after append operation is: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

You can observe that the new element is appended to the original list. Hence, it is modified. You can append elements of any data type or collection objects to the list using the append() method as follows.

myList = [1, 2, 3, 4, 5, 6, 7, 8, 9]
print("The original list is:", myList)
myList.append(10)
mySet = {10, 11, 12}
myStr = "java2blog"
myList.append(mySet)
myList.append(myStr)
print("The list after append operation is:", myList)

Output:

The original list is: [1, 2, 3, 4, 5, 6, 7, 8, 9]
The list after append operation is: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, {10, 11, 12}, 'java2blog']

Here, we have appended an integer, a set, and a string into a list originally containing integers. So, we can say that we can append any object to a list in python.

Append to array in Python

To append an element to an array, we can use the append() method as we did in the case of the lists. Here, The append() method accepts an element as an input argument and appends it to the end of the list as follows.

import array

myArr = array.array("i", [1, 2, 3, 4, 5, 6, 7, 8, 9])
print("The original array is:", myArr)
myArr.append(10)
print("The array after append operation is:", myArr)

Output:

The original array is: array('i', [1, 2, 3, 4, 5, 6, 7, 8, 9])
The array after append operation is: array('i', [1, 2, 3, 4, 5, 6, 7, 8, 9, 10])

The difference between the append() method for array objects and the append() method for lists is that you can only provide elements of the specified data type to the append() method when it is invoked on an array. The data type of the input argument should be that of the elements already present in the array. Otherwise, the append() method will raise the TypeError exception as follows.

import array

myArr = array.array("i", [1, 2, 3, 4, 5, 6, 7, 8, 9])
print("The original array is:", myArr)
myArr.append("java2blog")
print("The array after append operation is:", myArr)

Output:

Traceback (most recent call last):
  File "/home/aditya1117/PycharmProjects/pythonProject/string1.py", line 5, in <module>
    myArr.append("java2blog")
TypeError: an integer is required (got type str)

Here, we have tried to append a string to an array containing integers. Due to this, the program has run into the TypeError exception showing the message “TypeError: an integer is required (got type str)

Append to NumPy array in python

To append an element to a NumPy array, we can use the append() method defined in the NumPy module. The append() method defined in the NumPy module takes the array as the first input argument, the value to be appended to the array as the second input argument, and an optional argument axis as its third argument. The parameter axis has a default value 0. Upon execution, it returns a new array that has the input values appended to the input array. You can observe this in the following example.

import numpy

myArr = numpy.array([1, 2, 3, 4, 5, 6, 7, 8, 9])
print("The original array is:", myArr)
newArr = numpy.append(myArr, 10)
print("The array after append operation is:", newArr)

Output:

The original array is: [1 2 3 4 5 6 7 8 9]
The array after append operation is: [ 1  2  3  4  5  6  7  8  9 10]

The append() method returns a new array and the original array in which the values are appended doesn’t get modified. You can verify this by simply printing the array before and after the append operation.

import numpy

myArr = numpy.array([1, 2, 3, 4, 5, 6, 7, 8, 9])
print("The original array is:", myArr)
newArr = numpy.append(myArr, 10)
print("The array after append operation is:", newArr)
print("The original array after append operation is:", myArr)

Output:

The original array is: [1 2 3 4 5 6 7 8 9]
The array after append operation is: [ 1  2  3  4  5  6  7  8  9 10]
The original array after append operation is: [1 2 3 4 5 6 7 8 9]

If we do not specify the data type of the elements while creating the NumPy array, we can append the element of any data type into the array.

import numpy

myArr = numpy.array([1, 2, 3, 4, 5, 6, 7, 8, 9])
print("The original array is:", myArr)
newArr = numpy.append(myArr, "java2blog")
print("The array after append operation is:", newArr)

Output:

The original array is: [1 2 3 4 5 6 7 8 9]
The array after append operation is: ['1' '2' '3' '4' '5' '6' '7' '8' '9' 'java2blog']

Here, you can observe that we haven’t specified the data type of the array elements while creating the array. Hence, we are able to append an element of any data type to the array.

If we specify the data type of elements while creating the NumPy array, these arrays also have restrictions on the data types of the elements. However, when we append an element to the NumPy array, a new array is created. The new array can contain elements of any data type. We can say that we can append the element to the array using the append() method. However, in reality, a new array is created having elements of the original array and the element to be appended. So, the elements are not appended to the original array.

import numpy

myArr = numpy.array([1, 2, 3, 4, 5, 6, 7, 8, 9], dtype="i")
print("The original array is:", myArr)
newArr = numpy.append(myArr, "java2blog")
print("The array after append operation is:", newArr)

Output:

The original array is: [1 2 3 4 5 6 7 8 9]
The array after append operation is: ['1' '2' '3' '4' '5' '6' '7' '8' '9' 'java2blog']

Conclusion

In this article, we have discussed different types of arrays in python. We also discussed how we can append elements to an array in python using the various array implementations. 

I hope you enjoyed reading this article. Stay tuned for more informative articles.

Happy Learning!

]]>
https://java2blog.com/python-append-to-array/feed/ 0