Here are 10 Python snippets demonstrating how to work with CSV files using the pandas library for data reading, writing, and manipulation. Each snippet is separated by a delimiter.
Snippet 1: Reading a CSV File
import pandas as pd# Reading a CSV file into a DataFramedf = pd.read_csv('data.csv')print(df.head())# Display the first 5 rows
Snippet 2: Writing a DataFrame to a CSV File
import pandas as pd# Create a sample DataFramedata ={'Name':['Alice','Bob','Charlie'],'Age':[25,30,35]}df = pd.DataFrame(data)# Writing DataFrame to CSVdf.to_csv('output.csv',index=False)print("Data written to 'output.csv'")
Snippet 3: Reading a CSV File with Custom Delimiters
Snippet 4: Specifying Column Names While Reading CSV
Snippet 5: Skipping Rows While Reading CSV
Snippet 6: Reading a CSV with Specific Columns
Snippet 7: Handling Missing Data While Reading CSV
import pandas as pd
# Reading a CSV file with a custom delimiter (semicolon)
df = pd.read_csv('data.csv', delimiter=';')
print(df.head()) # Display the first 5 rows
import pandas as pd
# Reading a CSV file with custom column names
column_names = ['Name', 'Age', 'City']
df = pd.read_csv('data.csv', names=column_names, header=None)
print(df.head()) # Display the first 5 rows
import pandas as pd
# Reading a CSV file while skipping the first two rows
df = pd.read_csv('data.csv', skiprows=2)
print(df.head()) # Display the first 5 rows
import pandas as pd
# Reading specific columns from a CSV file
df = pd.read_csv('data.csv', usecols=['Name', 'Age'])
print(df.head()) # Display the first 5 rows
import pandas as pd
# Reading a CSV file and filling missing data with a default value
df = pd.read_csv('data.csv', na_values='NA')
df.fillna(0, inplace=True) # Replace all NaN with 0
print(df.head()) # Display the first 5 rows
import pandas as pd
# Create a new DataFrame
data = {'Name': ['David'], 'Age': [40], 'City': ['New York']}
df_new = pd.DataFrame(data)
# Appending new data to an existing CSV file
df_new.to_csv('data.csv', mode='a', header=False, index=False)
print("New data appended to 'data.csv'")
import pandas as pd
# Create a sample DataFrame
data = {'Name': ['Alice', 'Bob'], 'Age': [25, 30]}
df = pd.DataFrame(data)
# Writing DataFrame to CSV with a custom index
df.to_csv('output.csv', index_label='ID')
print("Data written to 'output.csv' with custom index.")
import pandas as pd
# Reading a CSV file with a specific encoding (e.g., UTF-8)
df = pd.read_csv('data.csv', encoding='utf-8')
print(df.head()) # Display the first 5 rows