Sunday, 19 December 2021

Python program for Array slicing, reshaping, concatenation and splitting in Numpy

 The Pandas Numpy library provides some useful methods to perform slicing, reshaping, and concatenation. The following program show you how to perform these operations

#a.Array slicing, reshaping, concatenation and splitting

#1.Slicing 
import numpy as np
import pandas as pd
a = np.arange(20) 
print("------------------------------------")
print("1.Slicing")
print("------------------------------------")
print("The array is :");
print(a)
print("Slicing of items starting from the index:")
print (a[2:8])


#2.reshaping
print("------------------------------------")
print("2.Reshaping")
print("------------------------------------")
data = pd.DataFrame(np.arange(6).reshape((2, 3)),
 index=pd.Index(['Ohio', 'Colorado'], name='state'),
 columns=pd.Index(['one', 'two', 'three'], name='number'))
print("------Before Reshaping--------------")
print(data)
result = data.stack()
print("------After Reshaping--------------")
print(result)


#3.Concatenation
print("------------------------------------")
print("3.concatenation")
print("------------------------------------")
s1 = pd.Series([0, 1], index=['a', 'b'])
s2 = pd.Series([2, 3, 4], index=['c', 'd', 'e'])
s3 = pd.Series([5, 6], index=['f', 'g'])
c=pd.concat([s1, s2, s3])
print(c)

print("------------------------------------")
print("3.Arrays Splitting")
print("------------------------------------")

arr = np.array([1, 2, 3, 4, 5, 6])
print("before splitting array is",arr)

new = np.array_split(arr, 3)
print(" New arrays are")
print(new[0])
print(new[1])
print(new[2])

The output is as follows

 

------------------------------------
1.Slicing
------------------------------------
The array is :
[ 0  1  2  3  4  5  6  7  8  9 10 11 12 13 14 15 16 17 18 19]
Slicing of items starting from the index:
[2 3 4 5 6 7]
------------------------------------
2.Reshaping
------------------------------------
------Before Reshaping--------------
number    one  two  three
state                    
Ohio        0    1      2
Colorado    3    4      5
------After Reshaping--------------
state     number
Ohio      one       0
          two       1
          three     2
Colorado  one       3
          two       4
          three     5
dtype: int32
------------------------------------
3.concatenation
------------------------------------
a    0
b    1
c    2
d    3
e    4
f    5
g    6
dtype: int64
------------------------------------
3.Arrays Splitting
------------------------------------
before splitting array is [1 2 3 4 5 6]
 New arrays are
[1 2]
[3 4]
[5 6]

0 comments:

Post a Comment

Note: only a member of this blog may post a comment.

Find Us On Facebook

python tutorial

More

C Programming

More

Java Tutorial

More

Data Structures

More

MS Office

More

Database Management

More
Top