ASSIGNMENT
ASSIGNMENT
Q.7 Explain Data frame in detail.
Answer :-Â
- A DataFrame is a two-dimensional, tabular data structure commonly used in Python for data analysis and manipulation.
- It is part of the pandas library, which is built on top of NumPy and provides powerful tools for handling structured data.
- A DataFrame is similar to a table in a relational database, an Excel spreadsheet, or a data frame in R. It consists of rows and columns, where:
- Rows represent individual observations or records.
- Columns represent variables or features, each with a label (column name).
Key Features of a DataFrame
Two-Dimensional Structure: Data is organized into rows and columns.
Heterogeneous Data: A DataFrame can contain different types of data in different columns (e.g., integers, floats, strings, or even objects).
Indexing: Each row and column is labeled using indexes for easy access and manipulation.
Mutable: DataFrames are mutable, meaning they can be modified after creation.
Powerful Operations: Supports filtering, grouping, merging, reshaping, and performing operations on data.
Creating a DataFrame
You can create a DataFrame in several ways using the pandas library. Below are some common approaches:
From a Dictionary
import pandas as pd
data = {
“Name”: [“Alice”, “Bob”, “Charlie”],
“Age”: [25, 30, 35],
“City”: [“New York”, “Los Angeles”, “Chicago”]
}df = pd.DataFrame(data)
print(df)
From a List of Dictionaries
import pandas as pd
data = [
{“Name”: “Alice”, “Age”: 25, “City”: “New York”},
{“Name”: “Bob”, “Age”: 30, “City”: “Los Angeles”},
{“Name”: “Charlie”, “Age”: 35, “City”: “Chicago”}
]df = pd.DataFrame(data)
print(df)
From a List of Lists
import pandas as pd
data = [
[“Alice”, 25, “New York”],
[“Bob”, 30, “Los Angeles”],
[“Charlie”, 35, “Chicago”]
]df = pd.DataFrame(data, columns=[“Name”, “Age”, “City”])
print(df)
From a NumPy Array
import pandas as pd
import numpy as np
data = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]])
df = pd.DataFrame(data, columns=[“A”, “B”, “C”])
print(df)
Common Attributes of a DataFrame
df.shape: Returns the dimensions of the DataFrame as (rows, columns).
print(df.shape) # Output: (3, 3)df.columns: Returns the column labels.
print(df.columns) # Output: Index([‘Name’, ‘Age’, ‘City’], dtype=’object’)df.index: Returns the row labels.
print(df.index) # Output: RangeIndex(start=0, stop=3, step=1)df.dtypes: Returns the data types of each column.
print(df.dtypes)df.head(): Displays the first few rows (default is 5).
print(df.head())df.tail(): Displays the last few rows (default is 5).
print(df.tail())
Common Operations on DataFrames
1. Selecting Data
Select a Single Column:
print(df[“Name”]) # Returns a SeriesSelect Multiple Columns:
print(df[[“Name”, “City”]]) # Returns a DataFrameSelect Rows by Index:
print(df.loc[0]) # Select row by label
print(df.iloc[1]) # Select row by position
2. Adding and Removing Columns
Add a New Column:
df[“Salary”] = [50000, 60000, 70000]
print(df)Remove a Column:
df.drop(“Salary”, axis=1, inplace=True)
print(df)
3. Filtering Data
Filter Rows Based on Conditions:
filtered_df = df[df[“Age”] > 25]
print(filtered_df)
4. Grouping and Aggregation
Group Data by a Column:
grouped = df.groupby(“City”)[“Age”].mean()
print(grouped)
5. Sorting Data
Sort by a Column:
df.sort_values(“Age”, ascending=False, inplace=True)
print(df)
6. Handling Missing Values
Check for Missing Values:
print(df.isnull())
Fill Missing Values:
df.fillna(“Unknown”, inplace=True)
Drop Rows with Missing Values
df.dropna(inplace=True)