PythonUNIT 5
PythonUNIT 5
Pandas is a powerful open-source data manipulation and analysis library built on top of
Python. It provides high-performance, easy-to-use data structures and data analysis tools,
making it a fundamental tool for data science, machine learning, and real-world data
processing.
It is built on NumPy and works seamlessly with other Python libraries like Matplotlib,
Seaborn, and Scikit-learn.
Installation
1. Use of Pandas
Definition
Pandas is used for data manipulation, analysis, and transformation, making it an essential
tool for handling structured data efficiently.
Read and write data from multiple formats like CSV, Excel, JSON, SQL, and HDF5.
Example:
import pandas as pd
Example:
Example:
df_filtered = df[df['Age'] > 30] # Select rows where Age is greater than 30
Example:
Example:
Example:
df['Age'].hist()
plt.show()
Advantages of Pandas
Disadvantages of Pandas
❌ Consumes high memory when working with large datasets.
❌ Not suitable for real-time applications due to single-thread execution.
❌ Complex syntax for beginners when dealing with multi-dimensional data.
2. Pandas Series
Definition
A Pandas Series is a one-dimensional labeled array that can hold any data type, such as
integers, floats, strings, and Python objects. It is similar to a column in an Excel spreadsheet
or a NumPy 1D array with labels.
import pandas as pd
series = pd.Series(data)
print(series)
Output:
go
0 10
1 20
2 30
3 40
dtype: int64
Here, the left column represents index values, and the right column represents actual data
values.
print(series)
Output:
A 100
B 200
C 300
dtype: int64
print(series.isnull())
3. Pandas DataFrames
Definition
A Pandas DataFrame is a two-dimensional table-like data structure with labeled rows and
columns, similar to an Excel spreadsheet or SQL table. It allows for efficient data
manipulation, analysis, and visualization.
Creating a DataFrame
import pandas as pd
data = {'Name': ['Alice', 'Bob', 'Charlie'], 'Age': [25, 30, 35], 'Salary': [50000, 60000, 70000]}
df = pd.DataFrame(data)
print(df)
Output:
0 Alice 25 50000
1 Bob 30 60000
2 Charlie 35 70000
Operations on DataFrames
Advantages of DataFrames
The read_csv() function in Pandas is used to read data from a CSV (Comma-Separated
Values) file into a DataFrame.
import pandas as pd
df = pd.read_csv("data.csv")
Introduction to Tkinter
What is Tkinter?
Tkinter is the standard Python library used for creating Graphical User Interface (GUI)
applications. It provides a simple yet powerful way to develop desktop applications using
Python.
Since Tkinter is included with Python, you usually don’t need to install it separately.
However, on some systems, you may need to install it manually:
pip install tk
1. Import Tkinter
Example:
import tkinter as tk
# Create main window
root = tk.Tk()
root.geometry("400x300")
root.mainloop()
Tkinter Widgets
1. Entry Widget (Text Input Field)
Definition
The Entry widget is used to take single-line input from the user, like entering a username or
password.
import tkinter as tk
root = tk.Tk()
root.geometry("300x200")
def get_text():
user_input = entry.get()
button.pack()
Advantages:
Disadvantages:
Creating a Label
label.pack(pady=10)
Advantages:
Disadvantages:
Creating a Button
def say_hello():
print("Hello, Tkinter!")
button.pack()
Advantages:
Disadvantages:
The Radiobutton widget allows users to select only one option from a list.
rb1.pack()
rb2.pack()
Advantages:
Disadvantages:
Limited use for multiple selections.
The Checkbutton widget allows users to select multiple options (like a checkbox).
var1 = tk.IntVar()
var2 = tk.IntVar()
cb1.pack()
cb2.pack()
Advantages:
Disadvantages:
import tkinter as tk
def login():
username = entry_username.get()
password = entry_password.get()
if username == "admin" and password == "password123":
else:
root = tk.Tk()
root.title("Login Form")
root.geometry("300x200")
label_username.pack()
entry_username = tk.Entry(root)
entry_username.pack()
label_password.pack()
entry_password.pack()
# Login Button
button_login.pack(pady=10)
Explanation:
2. Displays labels and entry fields for the username and password.
Not suitable for advanced GUI applications (like modern web apps).
To use MySQL in Python, you need to install the MySQL connector package using the
following command:
python
CopyEdit
import mysql.connector
# Establish connection
conn = mysql.connector.connect(
if conn.is_connected():
# Close connection
conn.close()
Explanation:
2. Connection parameters:
3. **`.is_connected
4o
You said:
connecting to databse using mysql : installing mysql connector , cursor() object , execute()
method , fetchall() method , creating a simple program to connect database explain each
point in detail like previous
ChatGPT said:
MySQL Connector is a Python library that enables Python programs to communicate with
MySQL databases. It allows users to execute SQL queries and perform operations like
inserting, updating, deleting, and retrieving data from MySQL databases.
To use MySQL with Python, you need to install the MySQL Connector package. Install it
using the following command:
Verifying Installation
import mysql.connector
To interact with a MySQL database, you must first establish a connection. The
mysql.connector.connect() function is used to connect to a MySQL server.
import mysql.connector
conn = mysql.connector.connect(
if conn.is_connected():
conn.close()
Explanation:
2. Connection Parameters:
A cursor is a Python object used to execute SQL queries. It allows you to perform CRUD
operations (Create, Read, Update, Delete) in the database.
The execute() method runs SQL queries to interact with the database. It is used for:
Creating tables
Inserting records
Updating records
Deleting records
Retrieving records
cursor.execute("""
name VARCHAR(255),
age INT
""")
The fetchall() method retrieves all rows from the database after executing a SELECT query. It
returns a list of tuples, where each tuple represents a row from the result set.
Example: Retrieving Data from the Database
# Display data
print(row)
Example Output:
import mysql.connector
conn = mysql.connector.connect(
host="localhost",
user="root",
password="password",
database="college"
cursor.execute("""
name VARCHAR(255),
age INT
""")
# Inserting a record
# Retrieving data
rows = cursor.fetchall()
# Printing records
print("Students List:")
print(row)
# Closing connection
conn.close()
Explanation:
Disadvantages