0% found this document useful (0 votes)
20 views11 pages

Python Modules and Data Analysis Techniques

This document provides examples of using various Python modules for data analysis and scientific computing. It covers: - Own modules and built-in modules - Date/time modules (time, datetime) - NumPy for efficient numerical operations on multidimensional arrays - SciPy for scientific computing (special functions, integration, Fourier transforms, linear algebra) - Pandas for data analysis and manipulation (DataFrames, slicing, merging, joining, concatenation, data munging) - Statistics functions (mean, median, mode, variance)

Uploaded by

Coding Knowledge
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
20 views11 pages

Python Modules and Data Analysis Techniques

This document provides examples of using various Python modules for data analysis and scientific computing. It covers: - Own modules and built-in modules - Date/time modules (time, datetime) - NumPy for efficient numerical operations on multidimensional arrays - SciPy for scientific computing (special functions, integration, Fourier transforms, linear algebra) - Pandas for data analysis and manipulation (DataFrames, slicing, merging, joining, concatenation, data munging) - Statistics functions (mean, median, mode, variance)

Uploaded by

Coding Knowledge
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd

##own module

Example:
import calculo as cu
a= [Link]
a(5,6)
Output:
11

## built in modules
**to get list of all module
Example:
help("modules")

**to get all func in module


Example:
from matplotlib import pyplot
print(dir(pyplot))

**to find path it search for module


Example:
import sys
print([Link])

##date and time


##time and datetime module
**time module
Example:
import time
a=[Link]()
b=[Link]()
d= [Link]()
e=[Link]()
f=[Link](d)
g=[Link]()
h=[Link]("%d/%m/%y")
#j="08-08-2019"
#i=[Link](j,"%d-%m-%y")
#answer is not coming for above comment check later
print(a)
print(b)
print(d)
print(e)
print(f)
print(g)
print(h)
#print(i)

Output:
Mon Feb 15 01:13:35 2021
1613331815.2928958
time.struct_time(tm_year=2021, tm_mon=2, tm_mday=15, tm_hour=1, tm_min=13,
tm_sec=35, tm_wday=0, tm_yday=46, tm_isdst=0)
time.struct_time(tm_year=2021, tm_mon=2, tm_mday=14, tm_hour=19, tm_min=43,
tm_sec=35, tm_wday=6, tm_yday=45, tm_isdst=0)
1613331815.0
Mon Feb 15 01:13:35 2021
15/02/21
**datetime module
Example:
import datetime
a=[Link](2019,6,7,4,30,54,678)
b=[Link]()
c=[Link]()
d=[Link] #also have month,hour,date
e=[Link](2019,5,8)
f=[Link](3,8,12)
g1=[Link](days=20)
g2=[Link](days=30)
g3=g1-g2
print(a)
print(b)
print(c)
print(d)
print(e)
print(f)
print(g3)
print(type(g3))

Output:
2019-06-07 04:30:54.000678
2021-02-15 01:29:28.706968
2021-02-15 01:29:28.706967
2021
2019-05-08
03:08:12
-10 days, 0:00:00
<class '[Link]'>

##Numpy
#### It store data as two dimensional array
Example:
import numpy as np
a=[Link]([(1,2,3),(4,5,6),(7,8,9)])
print(a)

Output:
[[1 2 3]
[4 5 6]
[7 8 9]]

##size compare of list and numpy


Example:
import numpy as np
import time
import sys

s=range(1000)
print([Link](1)*len(s)) # you getting size of some int and multiple by
len(s)

d=[Link](1000)
print([Link]*[Link])

Output:
28000
4000
##numpy is faster than list
Example:
import numpy as np
import time
import sys

size = 1000000

li1 = range(size)
li2 = range(size)

ny1 = [Link](size)
ny2 = [Link](size)

start = [Link]()
result = [(x,y) for x,y in zip(li1,li2)]
print(([Link]()-start)*1000)

start = [Link]()
result = ny1+ny2
print(([Link]()-start)*1000)

Output:
143.52774620056152
47.97053337097168

##dimension of array ,bitesize ,datatype, size, shape

Example:
import numpy as np

a=[Link]([(1,2,3),(4,5,6)])
b=[Link]([1,2,3])

print([Link])
print([Link])
print([Link])
print([Link])
print([Link])

print([Link])
print([Link])
print([Link])
print([Link])
print([Link])

Ouput:
2
4
int32
6
(2, 3)
1
4
int32
3
(3,)

##reshape and slicing and linespacing


Example:
import numpy as np

a=[Link]([(1,2,3,4),(3,4,5,6),(4,5,6,7)])
print(a)
print(a[0,1])
print(a[0:2,3])
print(a[0:,3])
print(" ")

a=[Link](4,3)
print(a)

c=[Link](1,5,10)
print(c)

Output:
[[1 2 3 4]
[3 4 5 6]
[4 5 6 7]]
2
[4 6]
[4 6 7]

[[1 2 3]
[4 3 4]
[5 6 4]
[5 6 7]]

[1. 1.44444444 1.88888889 2.33333333 2.77777778 3.22222222


3.66666667 4.11111111 4.55555556 5. ]

##min max
Example:
import numpy as np

a=[Link]([1,2,3])
print([Link]())
print([Link]())
print([Link]())

Output:
1
3
6

##axis,square root, standard diviasion


Example:
import numpy as np

a=[Link]([(1,2,3),(4,5,6)])
print([Link](axis=1))
print([Link](axis=0))

print([Link](a))
print([Link](a))

Output:
[ 6 15]
[5 7 9]
[[1. 1.41421356 1.73205081]
[2. 2.23606798 2.44948974]]
1.707825127659933

##aritmetic operation in numpy


Example:
import numpy as np

a=[Link]([(1,2,3),(4,5,6)])
b=[Link]([(1,2,3),(4,5,6)])

print(a+b)
print("")
print(a-b)
print("")
print(a*b)
print("")
print(a/b)
print("")
print(a-b)

Output:
[[ 2 4 6]
[ 8 10 12]]

[[0 0 0]
[0 0 0]]

[[ 1 4 9]
[16 25 36]]

[[1. 1. 1.]
[1. 1. 1.]]

#stacking -verticalstacking and horizontal stacking


#.ravel()
Example:
import numpy as np

a=[Link]([(1,2,3),(4,5,6)])
b=[Link]([(1,2,3),(4,5,6)])

print([Link]((a,b)))
print('')
print([Link]((a,b)))
print('')
print([Link]())

Output:
[[1 2 3]
[4 5 6]
[1 2 3]
[4 5 6]]
[[1 2 3 1 2 3]
[4 5 6 4 5 6]]

[1 2 3 4 5 6]

##sine and cosine function


Example:
import numpy as np
from matplotlib import pyplot as plt

x = [Link](0,3*[Link],0.1)
y = [Link](x) #you can give any like cos,sin,sec...

[Link](x,y)
[Link]()

Output:
do in python

##exponential and logarithmic function


Example:
import numpy as np
from matplotlib import pyplot as plt

ar = [Link]([1,2,3])
print([Link](ar))
print([Link](ar))
print(np.log10(ar))

Output:
[ 2.71828183 7.3890561 20.08553692]
[0. 0.69314718 1.09861229]
[0. 0.30103 0.47712125]

scipy
##help,info,source
Example:
import scipy
from scipy import cluster
help()
help(cluster)
[Link](cluster)
[Link](cluster)

Output: do in python

##special function
power and trignamentry
Example:
from scipy import special
a = special.exp10(2)

b = special.exp2(3)

c = [Link](90)
d = [Link](90)

print(a)
print(b)
print(c)
print(d)

Output:
100.0
8.0
-0.0
1.0

##integration Function
quad and doublequad function
Example:
from scipy import integrate
from scipy import special
a = [Link](lambda x:special.exp10(x),0,1)

print(a)

b = lambda x,y:x*y**2
c = lambda x: 1
d = lambda x:-1
e = [Link](b,0,2,c,d)

print(e)

Output:
(3.9086503371292665, 4.3394735994897923e-14)
(-0.0, 4.405142707569776e-14)

##Fourier transformations
Example:
from [Link] import fft,ifft
import numpy as np
a = [Link]([1,2,3])
b = fft(a)
c = ifft(a)
print(b)
print(c)

Output:
[ 6. -0.j -1.5+0.8660254j -1.5-0.8660254j]
[ 2. -0.j -0.5-0.28867513j -0.5+0.28867513j]

##linear algebra
matrix inverse
Example:
from scipy import linalg
import numpy as np
a = [Link]([(1,2),(3,4)])
b = [Link](a)
print(b)

Output:
[[-2. 1. ]
[ 1.5 -0.5]]

##interpolation function
Example:
import [Link] as plt
import numpy as np
from scipy import interpolate
x = [Link](5,20)
y = [Link](x/3.0)
f = interpolate.interp1d(x,y)
x1 = [Link](6,12)
y1 = f(x1)
[Link](x,y,'o',x1,y1,'--')
[Link]()

Output:
do in python

##pandas
Data analyisit
DataFrame ,slicing
Example:
import pandas as pd

web_data = {'Day':[1,2,3,4,5,6], 'Visitors':


[1000,700,6000,1000,400,350],'Bounce_rate':[20,20,23,15,10,34]}

df = [Link](web_data)

print(df)
print("\n")
print([Link](2))
print("\n")
print([Link](2))

Ouput:
Day Visitors Bounce_rate
0 1 1000 20
1 2 700 20
2 3 6000 23
3 4 1000 15
4 5 400 10
5 6 350 34

Day Visitors Bounce_rate


0 1 1000 20
1 2 700 20

Day Visitors Bounce_rate


4 5 400 10
5 6 350 34

merging
Example:
import pandas as pd

df1 = [Link]({'hpi':[80,90,70,60],'int_rate':[2,1,2,3],'ind_gdp':
[50,45,45,67]},
index = [2001,2002,2003,2004])

df2 = [Link]({'hpi':[80,90,70,60],'int_rate':[2,1,2,3],'ind_gdp':
[50,45,45,67]},
index = [2005,2006,2007,2008])

merge1 = [Link](df1,df2)
merge2 = [Link](df1,df2,on='hpi')

print(merge1)
print(merge2)

Output:
hpi int_rate ind_gdp
0 80 2 50
1 90 1 45
2 70 2 45
3 60 3 67
hpi int_rate_x ind_gdp_x int_rate_y ind_gdp_y
0 80 2 50 2 50
1 90 1 45 1 45
2 70 2 45 2 45
3 60 3 67 3 67

joing
Example:
import pandas as pd

df1 = [Link]({'int_rate':[2,1,2,3],'ind_gdp':[50,45,45,67]},
index = [2001,2002,2003,2004])

df2 = [Link]({'int_value':[50,44,64,33],'unemployment':[1,2,3,4]},
index = [2001,2002,2004,2004])

join1= [Link](df2)
print(join1)

Output:
do in python

Changing the index and column header


index change
Example:
import pandas as pd

df = {'day':[1,2,3,4],'visitors':[200,100,230,400],'bounce_rate':[20,45,50,31]}
e = [Link](df)
e.set_index('day',inplace=True)
print(e)

Output:
do in python

column header change


Example:
import pandas as pd
import [Link] as plt
from matplotlib import style
[Link]('fivethirtyeight')

df = {'day':[1,2,3,4],'visitors':[200,100,230,400],'bounce_rate':[20,45,50,31]}
e = [Link](df)
df = [Link](columns={'visitors':'users'})
print(df)

Output:
do in pyhton

Cancatenation
Example:
import pandas as pd

df1 = [Link]({'name':['sri','meen','puppy','rajan'],
'class':[10,11,12,1],
'salary':[100,200,300,400]},
index=[2001,2002,2003,2004])
df2 = [Link]({'name':['bala','eswari','selva','manian'],
'class':[3,4,5,6],
'salary':[1050,2600,3700,4800]},
index=[2005,2006,2007,2008])

concatenation =[Link]([df1,df2])
print(concatenation)

Output:
do in python

data munging
Example:
import pandas as pd

a = pd.read_csv('C:\\Users\\SRI RAJAN\\Documents\\[Link]', index_col=0)


b=a.to_html('[Link]')
#use in pycharm

Output:
do in pycharm

data difference 8:55 -- 8:59:30

Statistics for python- mean,median, mode,variance


Example:
from statistics import *
print(mean([1,1,1,1,2,3,3,3,4,5]))
print(mode([1,1,1,1,2,3,3,3,4,5]))
print(median([1,1,1,1,2,3,3,3,4,5]))
print(variance([1,1,1,1,2,3,3,3,4,5]))
Output:
2.4
1
2.5
2.0444444444444443

python for Hadoop:Pydoop 9:2:30

matplotlib
simple graph
Example:
from matplotlib import pyplot as plt
x = [1,2,3,4,5,6]
y = [6,1,3,6,4,7]

[Link]('simple graph')
[Link]('time')
[Link]('work')
[Link](x,y)

[Link]()

Output:
do in python

plot,bar,hist,scatter,stack plot(area graph),pie chart,subplot

Example:
search matplotlib graph in python

seaborn 9:36:00...see this


seaborn- scatter,line,catplot,
Example:
see in python file..... seaborn graph

univariate and bivariate


Example:
see in python file.... seaborn graph

multi-plot grid,pair grid


Example:
see in python file.... seaborn graph

plot aesthetics
Example:
see in python file.... seaborn graph

Common questions

Powered by AI

NumPy arrays support element-wise arithmetic operations, allowing for fast computation by automatically applying the operation to each element in the array. For example, given two NumPy arrays `a` and `b`, the expression `a+b` adds each corresponding pair of elements. This feature is vectorized, meaning it avoids the need for explicit loops, enhancing performance significantly compared to Python lists. Additionally, since NumPy operations are implemented in C, they are substantially faster as demonstrated by significant speed differences observed in performance timing tests . In contrast, Python list operations would require explicit loops and function calls, resulting in slower execution.

Pandas DataFrames provide simple methods to change both column headers and indexes, enhancing data clarity and accessibility. The `rename()` method allows swapping column names, facilitating clearer data representation and reference during analysis. `set_index()` can modify the DataFrame index, allowing efficient data retrieval by setting meaningful row labels . These transformations are crucial for preparing datasets for more accurate and effective analysis, enabling seamless integration into workflows where specific columns or indexes serve as keys for database operations or detailed reporting.

Integrating Scipy for Fourier transformations offers distinct advantages such as enhanced numerical precision, optimized algorithms, and support for non-standard data size through zero-padding. Utilizing `scipy.fftpack.fft()` and `scipy.fftpack.ifft()` supports fast computation of the Fourier Transform, necessary for applications like image and audio signal processing where frequency domain analysis is required. These implementations are generally more efficient and flexible than basic methods, enabling more complex transformations and computations directly compatible with advanced scientific workflows . Leveraging these advantages can improve accuracy and performance in real-time data analysis applications.

The Pandas library offers robust tools for integrating data manipulation in a Python workflow. For merging, Pandas provides `pd.merge()` to combine DataFrame objects by aligning them along a specified key column. DataFrame joining can be done with `df1.join(df2)`, which aligns indexes with different DataFrames to join columns from each. Concatenation with `pd.concat()` allows stacking or appending DataFrames either vertically or horizontally. These operations support complex data manipulation and preparation tasks such as aggregating datasets, cleaning, and transforming data ready for analysis . This flexibility makes Pandas indispensable for data analysis tasks.

Matplotlib offers extensive graph plotting capabilities for visualizing trigonometric functions, such as sine, cosine, and tangent. By utilizing NumPy to generate data points—such as `np.arange(0,3*np.pi,0.1)` for the x-values—and then computing corresponding y-values using trigonometric functions like `np.sin(x)` or `np.cos(x)`, users can plot these into clear graphs with `plt.plot(x, y)`, followed by `plt.show()` to display them . This approach is highly useful for mathematical demonstrations and analytical tasks requiring visual interpretation of periodic functions.

Using the `numpy.fft` module enables efficient computation of the discrete Fourier Transform (DFT) and its inverse on arrays. For instance, `fft(a)` computes the one-dimensional n-point DFT, which is useful in signal processing to analyze frequency components of a signal or data. Similarly, `ifft(a)` returns the one-dimensional inverse DFT, allowing conversion back to the time domain . In practice, these transformations can be applied in fields such as audio processing, image filtering, and solving differential equations by transforming signals from the time domain to the frequency domain, facilitating various analyses.

NumPy arrays are more memory efficient than Python lists when handling numerical data. When importing an integer list containing 1000 elements, for instance, the memory required is approximately 28,000 bytes as calculated by `sys.getsizeof(1)*len(s)` for a range object in Python. In contrast, a NumPy array with the same number of elements only requires about 4,000 bytes as noted by `d.size*d.itemsize` . This efficiency arises because NumPy arrays store data in a more compact and uniform manner using fixed data types, unlike lists that require additional memory for object references.

Scipy plays a vital role in scientific computing by providing advanced mathematical functions and capabilities. For linear algebra, Scipy offers methods in the `scipy.linalg` module for operations such as computing matrix inverses with `linalg.inv()`. This functionality is essential in solving systems of linear equations, performing eigenvalue computations, and other algebraic solutions . In interpolation, Scipy's `interpolate` module allows for `interp1d()` operations to create interpolating functions, useful in estimating data points within a range, thereby providing powerful tools for modeling and simulations in applied sciences . These capabilities enhance the efficiency and depth of computational analysis.

The `time` module in Python provides various utilities to handle time-related operations. For example, `time.ctime()` returns the current local time as a readable string, while `time.time()` gives the current time in seconds since the Epoch. `time.localtime()` and `time.gmtime()` convert a time expressed in seconds since the Epoch to a time structure that is either in local or GMT time, respectively. The method `time.strftime()` can format a time structure into a string based on the specified format . These functions provide flexibility in both retrieving and manipulating time-related data.

The `datetime.timedelta` class in Python is used for representing the difference between two dates or times. It computes the duration by storing days, seconds, and microseconds, such as when subtracting one `datetime` object from another. For example, subtracting `timedelta(days=30)` from `timedelta(days=20)` results in `-10 days`, which can be used to calculate and represent time intervals . This class facilitates operations such as determining the number of days between two specific dates or calculating expiration periods.

You might also like