[go: up one dir, main page]

0% found this document useful (0 votes)
3 views20 pages

I.P File

I.p files of python and SQL

Uploaded by

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

I.P File

I.p files of python and SQL

Uploaded by

manshibhati4002
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 20

PYTHON PROGRAMMES

1.Renaming Rows and Columns in a DataFrame

import pandas as pd
df = pd.DataFrame({'A': [1, 2, 3], 'B': [4, 5, 6]})
df.rename(columns={'A': 'Alpha', 'B': 'Beta'}, inplace=True)
print(df)

Output:

Alpha Beta
0 1 4
1 2 5
2 3 6

---

2.Vector Operations on Series Objects

import pandas as pd
series1 = pd.Series([1, 2, 3])
series2 = pd.Series([4, 5, 6])
result = series1 + series2
print(result)

Output:

0 5
1 7
2 9
dtype: int64

---

3. Arithmetic Operations on Series Objects

import pandas as pd
series = pd.Series([1, 2, 3])
result = series * 10
print(result)
Output:

0 10
1 20
2 30
dtype: int64

---

4. Extracting Slices from Series Objects

import pandas as pd
series = pd.Series([10, 20, 30, 40, 50])
slice_series = series[1:4]
print(slice_series)

Output:

1 20
2 30
3 40
dtype: int64

---

5. Making a Dictionary and Filtering Entries in Series Object

import pandas as pd
data = {'a': 10, 'b': 20, 'c': 30, 'd': 40}
series = pd.Series(data)
print(series)

Output:

a 10
b 20
c 30
d 40
dtype: int64

---

6. Creating and Manipulating ndarrays

import numpy as np
arr_1d = np.array([1, 2, 3, 4])
arr_2d = np.array([[1, 2], [3, 4]])
print(arr_1d)
print(arr_2d)

Output:

[1 2 3 4]
[[1 2]
[3 4]]

---

7. Sorting Values in a Series

import pandas as pd
series = pd.Series([20, 10, 30, 40])
sorted_series = series.sort_values()
print(sorted_series)

Output:

1 10
0 20
2 30
3 40
dtype: int64

---

8. Using head() and tail() Functions in Series

import pandas as pd
series = pd.Series([10, 20, 30, 40, 50, 60])
print(series.head(3))
print(series.tail(2))

Output:

0 10
1 20
2 30
dtype: int64

4 50
5 60
dtype: int64

---

9. Handling NaN (Not a Number) Values

import pandas as pd
import numpy as np
series = pd.Series([1, 2, np.nan, 4, 5])
series_filled = series.fillna(0)
print(series_filled)

Output:

0 1.0
1 2.0
2 0.0
3 4.0
4 5.0
dtype: float64

---

10. Selecting and Accessing a Column

import pandas as pd
df = pd.DataFrame({'A': [1, 2, 3], 'B': [4, 5, 6]})
column_a = df['A']
print(column_a)

Output:

0 1
1 2
2 3
Name: A, dtype: int64

---

11. Selecting Rows and Columns from a DataFrame

import pandas as pd
df = pd.DataFrame({'A': [1, 2, 3], 'B': [4, 5, 6]})
row_column_selection = df.loc[0, 'A']
print(row_column_selection)

Output:

---

12. Selecting DataFrame Rows and Columns Based on Boolean


Conditions

import pandas as pd
df = pd.DataFrame({'A': [1, 2, 3], 'B': [4, 5, 6]})
filtered_df = df[df['A'] > 1]
print(filtered_df)

Output:

A B
1 2 5
2 3 6

---

13. Adding and Modifying a Column in a DataFrame

import pandas as pd
df = pd.DataFrame({'A': [1, 2, 3]})
df['B'] = [4, 5, 6]
df['A'] = df['A'] * 10
print(df)

Output:

A B
0 10 4
1 20 5
2 30 6

---

14. Adding and Modifying a Row in a DataFrame


import pandas as pd
df = pd.DataFrame({'A': [1, 2], 'B': [4, 5]})
df.loc[2] = [3, 6]
df.loc[1] = [10, 50]
print(df)

Output:

A B
0 1 4
1 10 50
2 3 6

---

15. Deleting Columns from a DataFrame

import pandas as pd
df = pd.DataFrame({'A': [1, 2, 3], 'B': [4, 5, 6]})
df.drop('B', axis=1, inplace=True)
print(df)

Output:

A
0 1
1 2
2 3

---

16. Deleting Rows from a DataFrame

import pandas as pd
df = pd.DataFrame({'A': [1, 2, 3], 'B': [4, 5, 6]})
df.drop(1, axis=0, inplace=True)
print(df)

Output:

A B
0 1 4
2 3 6

---
17. Boolean Indexing in Series Objects

import series = pd.Series([10, 15, 20, 25])


filtered_series = series[series > 15]
print(filtered_series)

Output:

2 20
3 25
dtype: int64

---

18. Deleting Rows or Columns in a DataFrame

Code:

import pandas as pd

df = pd.DataFrame({'A': [1, 2, 3], 'B': [4, 5, 6]})


df = df.drop(columns=['A']) # Delete column 'A'
print(df)

Output:

B
0 4
1 5
2 6

---

19. Accessing Individual Elements in a DataFrame

Code:

import pandas as pd

df = pd.DataFrame({'A': [1, 2, 3], 'B': [4, 5, 6]})


element = df.at[0, 'A'] # Access specific element
print(element)

Output:
1

20.Bar Chart

Program:

import matplotlib.pyplot as plt

students = ['John', 'Jane', 'Alice', 'Mark']


marks = [85, 90, 88, 76]
plt.bar(students, marks, color='blue')
plt.title("Marks of Students")
plt.xlabel("Students")
plt.ylabel("Marks")
plt.show()

Output :

---

21. Line Graph

Program:

import matplotlib.pyplot as plt

years = [2018, 2019, 2020, 2021, 2022]


profits = [5, 8, 10, 15, 20]
plt.plot(years, profits, marker='o', color='green', linestyle='--')
plt.title("Company Growth Over Years")
plt.xlabel("Year")
plt.ylabel("Profit (in million dollars)")
plt.show()

Output :

---

22. Pie Chart

Program:

import matplotlib.pyplot as plt

categories = ['Rent', 'Groceries', 'Transport', 'Entertainment', 'Savings']


expenses = [40, 25, 15, 10, 10]
plt.pie(expenses, labels=categories, autopct='%1.1f%%', startangle=140)
plt.title("Monthly Expense Distribution")
plt.show()

Output :
---

23.Histogram

Program:

import matplotlib.pyplot as plt

Data: Marks of students in a class


marks = [56, 45, 67, 70, 89, 76, 88, 95, 85, 60, 78, 83, 55, 66, 72]
plt.hist(marks, bins=5, color='purple', edgecolor='black')
plt.title("Distribution of Marks")
plt.xlabel("Marks Range")
plt.ylabel("Frequency")
plt.show()

Output :

---
24. Creating a CSV File

This Python script will create a CSV file named students.csv with sample student data.

import csv

students_data = [ ["StudentID", "Name", "Age", "Class", "Marks"],


[1, "John Doe", 16, "10", 85],
[2, "Jane Smith", 17, "11", 90],
[3, "Alice Brown", 16, "10", 88],
[4, "Tom Green", 18, "12", 92]]

with open("students.csv", mode="w", newline="") as file:


writer = csv.writer(file)
writer.writerows(students_data)

print("CSV file 'students.csv' created successfully.")

Expected Output After Running the Script:

CSV file 'students.csv' created successfully.

Contents of students.csv:

StudentID,Name,Age,Class,Marks
1,John Doe,16,10,85
2,Jane Smith,17,11,90
3,Alice Brown,16,10,88
4,Tom Green,18,12,92

----

25. Reading the CSV File

Next, we will read the contents of students.csv and display the rows.

import csv

with open ("students.csv", mode="r") as file:


csv_reader = csv.reader(file)
for row in csv_reader:
print(row)

Expected Output After Running the Read Script:


['StudentID', 'Name', 'Age', 'Class', 'Marks']
['1', 'John Doe', '16', '10', '85']
['2', 'Jane Smith', '17', '11', '90']
['3', 'Alice Brown', '16', '10', '88']
['4', 'Tom Green', '18', '12', '92']

-----
SQL QUERIES

1. Create Database and Table

SQL Command:

CREATE DATABASE School;


USE School;

CREATE TABLE Students (


StudentID INT PRIMARY KEY,
Name VARCHAR(100),
Age INT,
Class VARCHAR(10),
Marks INT );

Output: The table structure for Students:

---

2. Insert Data into Table

SQL Command:

INSERT INTO Students (StudentID, Name, Age, Class, Marks)


VALUES
(1, 'John Doe', 16, '10', 85),
(2, 'Jane Smith', 17, '11', 90),
(3, 'Alice Brown', 16, '10', 88);

Resulting Data in the Students Table:

---

3. Select All Records

SQL Command:

SELECT * FROM Students;

Output:

---

4. Select Specific Columns

SQL Command:

SELECT Name, Marks FROM Students;

Output:
---

5. Filter Data Using WHERE Clause

SQL Command:

SELECT * FROM Students WHERE Marks > 85;

Output:

---

6. Update Records

SQL Command:

UPDATE Students
SET Marks = 92
WHERE StudentID = 2;

Updated Table:
---

7. Delete Records

SQL Command:

DELETE FROM Students WHERE StudentID = 3;

Updated Table:

---

8. Order Records

SQL Command:

SELECT * FROM Students ORDER BY Marks DESC;

Output:
---

9. Viewing the Structure of a Table

SQL Command:

DESCRIBE Students;

Output:

---

10. Aggregate Functions

SQL Command:

SELECT AVG(Marks) AS AverageMarks, MAX(Marks) AS HighestMarks, MIN(Marks) AS


LowestMarks
FROM Students;

Output:
---

11. Group Clause

SQL Command:

SELECT Class, AVG(Marks) AS AverageMarks


FROM Students
GROUP BY Class;

Output:

---

12. Having Clause

SQL Command:

SELECT Class, AVG(Marks) AS AverageMarks


FROM Students
GROUP BY Class
HAVING AVG(Marks) > 85;

Output:

---

13. Inserting Data into Another Table

SQL Command:

CREATE TABLE Teachers


(TeacherID INT PRIMARY KEY,
Name VARCHAR(100),
Class VARCHAR(10));

INSERT INTO Teachers (TeacherID, Name, Class)


SELECT StudentID, Name, Class FROM Students;

Resulting Data in Teachers Table:

---

14. Modifying Data in a Table

SQL Command:

UPDATE Students
SET Class = '12'
WHERE StudentID = 1;

Updated Table:

---

15. Eliminating Redundant Data

SQL Command:

CREATE TABLE CourseRegistrations (


StudentID INT,
CourseID INT,
PRIMARY KEY (StudentID, CourseID));

INSERT INTO CourseRegistrations (StudentID, CourseID)


VALUES (1, 101), (2, 102), (1, 101), (3, 103);

DELETE FROM CourseRegistrations


WHERE (StudentID, CourseID) NOT IN (
SELECT MIN(StudentID), MIN(CourseID)
FROM CourseRegistrations
GROUP BY StudentID, CourseID );

Resulting Table in CourseRegistrations:

---

16. Alter Table

SQL Command:

ALTER TABLE Students


ADD Email VARCHAR(100);

Updated Table Structure of Students:

---

You might also like