0% found this document useful (0 votes)
6 views14 pages

Python Data Visualization and Analysis

Uploaded by

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

Python Data Visualization and Analysis

Uploaded by

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

example :1Write a program to display line chart from (2,5) to (9,10).

import [Link] as plt

# Define the points

x_values = [2, 9]

y_values = [5, 10]

# Create the line chart

[Link](x_values, y_values,color='purple', marker='*')

# Add labels and title

[Link]('Line Chart from (2,5) to (9,10)')

[Link]('X-axis')

[Link]('Y-axis')

# Set the limits for x and y axes

[Link](0, 10)

[Link](0, 12)

# Show grid

[Link]()

# Display the plot

[Link]() OUTPUT:
#example:2 calculate BMI USING NUMPY ARRAY

# Create 2 new lists height and weight

height = [1.87, 1.87, 1.82, 1.91, 1.90, 1.85]

weight = [81.65, 97.52, 95.25, 92.98, 86.18, 88.45]

print(type(height))

# Import the numpy package as np

import numpy as np

# Create 2 numpy arrays from height and weight

np_height = [Link](height)

np_weight = [Link](weight)

print(type(np_height))

print(np_height)

print(np_weight)

# Calculate bmi

bmi = np_weight / np_height ** 2

# Print the result

print(bmi)

OUTPUT:

<class 'list'>

<class '[Link]'>

[1.87 1.87 1.82 1.91 1.9 1.85]

[81.65 97.52 95.25 92.98 86.18 88.45]

[23.34925219 27.88755755 28.75558507 25.48723993 23.87257618 25.84368152]

[Link] a program to display a scatter chart for the following points (2,5),

(9,10),(8,3),(5,7),(6,18).

import [Link] as plt

# Define the points


x_values = [2, 9, 8, 5, 6]

y_values = [5, 10, 3, 7, 18]

# Create the scatter chart

[Link](x_values, y_values, color='green', marker='*')

# Add labels and title

[Link]('Scatter Chart for Given Points')

[Link]('X-axis')

[Link]('Y-axis')

# Set the limits for x and y axes

[Link](0, 10)

[Link](0, 20)

# Show grid

[Link]()

# Display the plot

[Link]() OUTPUT:
[Link] a program to calculate mean, median and mode using Numpy.

import numpy as np

import pandas as pd

# create a sample salary table

salary = [Link]({

'employee_id': ['001', '002', '003', '004', '005', '006', '007',

'008', '009', '010'],

'salary': [50000, 65000, 55000, 45000, 70000, 60000, 55000, 45000,

80000, 70000]

})

print(salary)

# calculate mean

mean_salary = [Link](salary['salary'])

print('Mean salary:', mean_salary)

# calculate median

median_salary = [Link](salary['salary'])

print('Median salary:', median_salary)

# calculate mode

mode_salary = salary['salary'].mode()[0]

print('Mode salary:', mode_salary)

output:

employe_id salary

0 001 50000

1 002 65000

2 003 55000

3 004 45000
4 005 70000

5 006 60000

6 007 55000

7 008 45000

8 009 80000

9 010 70000

Mean salary: 59500.0

Median salary: 57500.0

Mode salary: 45000

5. Write a program to add the elements of the two lists.

import numpy as np

# initializing lists

test_list1 = [1, 3, 4, 6, 8]

test_list2 = [4, 5, 6, 2, 10]

# printing original lists

#print(test_list1)

print("Original list 1 : " + str(test_list1))

print("Original list 2 : " + str(test_list2))

# using [Link]() to add two lists

res_array = [Link](test_list1) + [Link](test_list2)

print("Resultant array is : " + str(res_array))

res_list = res_array.tolist()

# printing resultant list

print("Resultant list is : " + str(res_list))

output:
Original list 1 : [1, 3, 4, 6, 8]

Original list 2 : [4, 5, 6, 2, 10]

Resultant array is : [ 5 8 10 8 18]

Resultant list is : [5, 8, 10, 8, 18]


6. # To calculate Area and Perimeter of a rectangle
L=int(input("Length"))
B=int(input("Breadth"))
Area=L*B
Perimeter=2*(L+B)
print("area:", Area)
print("Perimeter:",Perimeter)
output:
Length 15
Breadth 17
area: 255
Perimeter: 64
7. #sample program for string data types
str="artificial+intelligence"
print(str)
print(str[0]);
print(str[2:8])
print(str[4:9])
print(str[3])
print(str[3:])
print(str*2)
print(str+'good morning')
#updating string
var1='python programming'
print(var1)
print(var1[:12])
print("updated string:",var1[:18]+'language')
output:
artificial+intelligence
a
tifici
ficia
i
ificial+intelligence
artificial+intelligenceartificial+intelligence
artificial+intelligencegood morning
python programming
python progr
updated string: python programminglanguage

8. #sample program for list data types


list=[29,750,37,12,345,67,89,67,78,89]
list1=['home','sweet ']
print(list)
print(list[0]);
print(list[2:8])
print(list[3:9])
print(list[3])
print(list[3:])
print(list1*2 )
print(list+list1)
output:
[29, 750, 37, 12, 345, 67, 89, 67, 78, 89]
29
[37, 12, 345, 67, 89, 67]
[12, 345, 67, 89, 67, 78]
12
[12, 345, 67, 89, 67, 78, 89]
['home', 'sweet ', 'home', 'sweet ']
[29, 750, 37, 12, 345, 67, 89, 67, 78, 89, 'home', 'sweet ']
9. # sample program for list function()
list=[10,20,30,40,50,60]
print(list)
[Link](70)
print(list)
[Link](4)
print(list)
[Link](60)
print(list)
[Link]()
print(list)
[Link]()
print(list)
output:
[10, 20, 30, 40, 50, 60]
[10, 20, 30, 40, 50, 60, 70]
[10, 20, 30, 40, 60, 70]
1
[70, 60, 40, 30, 20, 10]
[10, 20, 30, 40, 60, 70]
10. #sample program for tuple data types
tuple=('physics',786,2.25,'chemistry',750,10,20,30,40)
print(tuple);
tuple1=('computer',999)
print(tuple[0]);
print(tuple[2:8])
print(tuple[3:9])
print(tuple[3])
print(tuple[3:])
print(tuple*2 )
print(tuple+tuple1)
output:
('physics', 786, 2.25, 'chemistry', 750, 10, 20, 30, 40)
physics
(2.25, 'chemistry', 750, 10, 20, 30)
('chemistry', 750, 10, 20, 30, 40)
chemistry
('chemistry', 750, 10, 20, 30, 40)
('physics', 786, 2.25, 'chemistry', 750, 10, 20, 30, 40, 'physics', 786, 2.25,
'chemistry', 750, 10, 20, 30, 40)
('physics', 786, 2.25, 'chemistry', 750, 10, 20, 30, 40, 'computer', 999)
11. #sample program for condition statement(if…elif…)
a = int(input("Enter a number : "))
if a%2 == 0 and a >50:
# Even and > 50
print("Your number is even and greater than 50.")
elif a%2 == 0 and a <50:
# Even and < 50
print("Your number is even and smaller than 50.")
elif a%2 == 0 and a == 50:
# Even and == 50
print("Your number is even and equal to 50.")
else:
print ("Your number is odd.",)
output:
Enter a number : 204
Your number is even and greater than 50.
12. #sample program for ( dictionary')
dict={}
dict['one']='this is dictionary'
dict[2]='python programming'
tinydict={'name':'priya','code':1080,'dept':'admin'}
print(dict['one'])
print(dict[2])
print(tinydict)
print([Link]())
print([Link]())
output:
this is dictionary
python programming
{'name': 'priya', 'code': 1080, 'dept': 'admin'}
dict_keys(['name', 'code', 'dept'])
dict_values(['priya', 1080, 'admin'])

13.# sample program for BAR GRAPH


import [Link] as plt
Info = ['gold', 'Silver', 'Bronze', 'Total']
Australia =[80, 59, 59,198]
[Link](Info, Australia)
[Link](0, 200)
[Link]("Medal type")
[Link]("Australia Medal count")
[Link]( )

OUTPUT:
14. # sample program IN Python USING CSV FILE
# Import pandas as pd
import pandas as pd

# Import the [Link] data: cars


cars = pd.read_csv("[Link]",sep=',')

# Display the first 10 rows


print([Link](10))
OUTPUT:
Car Name Model Price
0 Toyota Camry 24000
1 Honda Civic 22000
2 Ford Focus 19000
3 Chevrolet Malibu 23000
4 Nissan Altima 25000
5 Hyundai Elantra 21000
6 Volkswagen Jetta 20000
7 Subaru Impreza 23000
8 Kia Forte 21000
9 Mazda CX-5 27000

15. # Simple program in Python USING PANDAS


dict = {"country": ["Brazil", "Russia", "India", "China", "South Africa"],
"capital": ["Brasilia", "Moscow", "New Dehli", "Beijing", "Pretoria"],
"area": [8.516, 17.10, 3.286, 9.597, 1.221],
"population": [200.4, 143.5, 1252, 1357, 52.98] }

import pandas as pd
br = [Link](dict)
print(br)

# Set the index for brics


[Link] = ["BR", "RU", "IN", "CH", "SA"]

# Print out brics with new index values


print(br)
OUTPUT:
country capital area population
0 Brazil Brasilia 8.516 200.40
1 Russia Moscow 17.100 143.50
2 India New Dehli 3.286 1252.00
3 China Beijing 9.597 1357.00
4 South Africa Pretoria 1.221 52.98
country capital area population
BR Brazil Brasilia 8.516 200.40
RU Russia Moscow 17.100 143.50
IN India New Dehli 3.286 1252.00
CH China Beijing 9.597 1357.00
SA South Africa Pretoria 1.221 52.98

Common questions

Powered by AI

Using Numpy to calculate BMI enhances efficiency because it operates over entire arrays with highly optimized C-based algorithms, which is faster than traditional loops that process one element at a time in Python. This is evident in the concise operation `np_weight / np_height ** 2`, which performs element-wise calculations on arrays instead of iterative approaches .

Matplotlib's flexibility in generating various chart types, such as line, scatter, and bar charts, as demonstrated, provides a comprehensive toolkit for visually representing data in Python. It facilitates customization of axes, labels, and colors, making it adaptable to any dataset requirements and improving the interpretability of data insights .

Tuples are effective for storing fixed data sequences because of their immutability, which guarantees data consistency, making them suitable for representing constant datasets. Their use allows for cleaner code and improved performance in situations that do not require data modification, as shown in stored strings and numbers .

The CSV reading capability in Pandas offers unique benefits such as scalable data handling, seamless integration with DataFrame operations for filtering, grouping, and statistics, and the ability to process large datasets using less memory through optimized C-based operations. This allows for convenient manipulation and analysis of data compared to traditional CSV parsing methods .

Python dictionaries provide a more reliable structure for storing heterogeneous data as they use key-value pairs allowing for direct data retrieval without the need for searching. Unlike lists, dictionaries guarantee O(1) average time complexity for lookups, insertions, and deletions, which significantly enhances performance when dealing with large datasets or frequent access patterns, as seen in examples of dictionary use for flexible data storage .

Using user input to determine the area and perimeter of geometric shapes introduces flexibility in code execution, as it allows dynamic calculation based on variable dimensions. However, it also necessitates error handling for non-numeric inputs and should consider validation for logical values to ensure accurate calculations .

Labeled data in Pandas DataFrames allows for easier data manipulation by providing meaningful indexing and column labeling, which enables selecting, filtering, and updating data using labels instead of positional indexing. This reduces errors and improves code readability and maintenance, as seen in operations like setting the DataFrame index and easily accessing columns by name .

Matplotlib is preferred for creating basic plots in Python due to its comprehensive documentation, ease of use for simple plots, and high customizability. It acts as the foundation for advanced libraries like Seaborn and offers flexibility for various chart types. Compared to newer libraries, Matplotlib remains user-friendly for beginners while allowing complex visual adjustments, despite a steeper learning curve for styled plots .

The mode calculation in Pandas leverages its built-in function `mode()`, which efficiently computes the most frequent value in a series with less manual overhead. This method is preferred over manual implementations as it is optimized for performance, handles ties, and is less error-prone, especially with extensive datasets .

Calculating statistics such as mean, median, and mode using Pandas is structurally simpler and computationally faster than manual methods. Pandas provides built-in methods that abstract complexity, enabling concise code that seamlessly operates on data within DataFrames, greatly enhancing efficiency and readability over manual iterative computations .

You might also like