Open Tolajoy opened 1 year ago
import pandas as pd
data = { 'Name': ['John', 'Emma', 'Peter', 'Lisa'], 'Age': [25, 30, 35, 27], 'City': ['New York', 'London', 'Paris', 'Tokyo'] }
df = pd.DataFrame(data)
print("Original Dataset:") print(df) print()
print("Accessing Columns:") print(df['Name']) # Access a single column print(df[['Name', 'Age']]) # Access multiple columns print()
print("Accessing Rows:") print(df.loc[0]) # Access a single row by label print(df.iloc[2]) # Access a single row by index print()
print("Filtering Rows:") filtered_df = df[df['Age'] > 27] # Filter rows where age is greater than 27 print(filtered_df) print()
print("Adding a New Column:") df['Profession'] = ['Engineer', 'Doctor', 'Teacher', 'Artist'] print(df) print()
print("Sorted Dataset:") sorted_df = df.sort_values('Age') print(sorted_df) print()
import pandas as pd
Create a sample dataset
data = { 'Name': ['John', 'Emma', 'Peter', 'Lisa'], 'Age': [25, 30, 35, 27], 'City': ['New York', 'London', 'Paris', 'Tokyo'] }
Convert the dictionary to a pandas DataFrame
df = pd.DataFrame(data)
Display the dataset
print("Original Dataset:") print(df) print()
Accessing columns
print("Accessing Columns:") print(df['Name']) # Access a single column print(df[['Name', 'Age']]) # Access multiple columns print()
Accessing rows
print("Accessing Rows:") print(df.loc[0]) # Access a single row by label print(df.iloc[2]) # Access a single row by index print()
Filtering rows
print("Filtering Rows:") filtered_df = df[df['Age'] > 27] # Filter rows where age is greater than 27 print(filtered_df) print()
Adding a new column
print("Adding a New Column:") df['Profession'] = ['Engineer', 'Doctor', 'Teacher', 'Artist'] print(df) print()
Sorting the dataset
print("Sorted Dataset:") sorted_df = df.sort_values('Age') print(sorted_df) print()