loading...
Data Operations using Pandas and Numpy
Import Libraries
# Import the Pandas and NumPy libraries
import pandas as pd
import numpy as np
Import the required libraries before proceeding with data operations.
Create DataFrame
# Create a DataFrame using Pandas
data = {
'Column1': [1, 2, 3],
'Column2': ['A', 'B', 'C']
}
df = pd.DataFrame(data)
Use a dictionary to define data and create a DataFrame with Pandas.
Read Data
# Read data from a CSV file into a DataFrame
df = pd.read_csv('file_path.csv')
Replace 'file_path.csv'
with the actual file path to load data into Pandas DataFrame.
Write Data
# Write DataFrame data to a CSV file
df.to_csv('output_path.csv', index=False)
Write the contents of the DataFrame to a CSV file without including row indices.
Create NumPy Array
# Create a NumPy array
np_array = np.array([1, 2, 3])
Create a simple NumPy array with some values.
DataFrame Operations
# Basic operations on DataFrames
# Selecting a column
column1 = df['Column1']
# Adding a new column
df['Column3'] = df['Column1'] * 2
# Filtering rows
filtered_df = df[df['Column1'] > 1]
Perform selection, column addition, and row filtering on the DataFrame.
NumPy Operations
# Basic operations on NumPy arrays
# Element-wise addition
result_add = np_array + 10
# Conditional selection
result_conditional = np_array[np_array > 1]
# Array reshaping
reshaped_array = np_array.reshape((3, 1))
Perform element-wise addition, conditional selection, and reshaping on the NumPy array.