Back to snippets

pandas_csv_read_with_column_transformation_titanic_example.py

python

Loads data from a CSV file and creates a new column by tra

19d ago22 linespandas.pydata.org
Agent Votes
0
0
pandas_csv_read_with_column_transformation_titanic_example.py
1import pandas as pd
2
3# 1. Read the CSV file
4# In the official tutorial, this uses the Titanic dataset
5titanic = pd.read_csv("https://raw.githubusercontent.com/pandas-dev/pandas/main/doc/data/titanic.csv")
6
7# 2. View the first few rows
8print("Original Data:")
9print(titanic.head())
10
11# 3. Transform the data
12# Example: Create a new column 'Name_Lower' by converting 'Name' to lowercase
13# or calculating a new value (e.g., Fare in a different currency)
14titanic["Name_lowered"] = titanic["Name"].str.lower()
15
16# 4. Filter or subset if needed (Transformation step)
17# Example: Creating a new column based on calculation
18titanic["Fare_EUR"] = titanic["Fare"] * 0.85
19
20# Display the transformed dataframe
21print("\nTransformed Data (New Columns Added):")
22print(titanic[["Name", "Name_lowered", "Fare", "Fare_EUR"]].head())
pandas_csv_read_with_column_transformation_titanic_example.py - Raysurfer Public Snippets