Notice: This page requires JavaScript to function properly.
Please enable JavaScript in your browser settings or update your browser.
Apprendre Changing the Data Type | Brief Introduction
Data Preprocessing

book
Changing the Data Type

You already know how to change the data type from string to number, for example. But let's take a closer look at this small but important task.

Let's start by changing the data type from string to datetime. Most often, you will need this to work with time series. You can perform this operation using the .to_datetime() method:

python
df['Date'] = pd.to_datetime(df['Date'], format='%Y%m%d')

To convert a string to a bool - use the .map() method on the column whose values you want to change:

python
df['C1'] = df['C1'].map({'yes': True, 'no': False})

For example, if you have a price column that looks like "$198,800" and you want to turn it into a float - you should create custom transformation functions:

import pandas as pd
import re

# Create simple dataset
df = pd.DataFrame(data={'Price':['$4,122.94', '$1,002.3']})

# Create a custom function to transform data
# x - value from column
def price2int(x):
return float(re.sub(r'[\$\,]', '', x))

# Use custom transformation on a column
df['Price'] = df['Price'].apply(price2int)
12345678910111213
import pandas as pd import re # Create simple dataset df = pd.DataFrame(data={'Price':['$4,122.94', '$1,002.3']}) # Create a custom function to transform data # x - value from column def price2int(x): return float(re.sub(r'[\$\,]', '', x)) # Use custom transformation on a column df['Price'] = df['Price'].apply(price2int)
copy
Tâche

Swipe to start coding

Read the sales_data_types.csv dataset and change the data type in the Active column from str to bool.

Solution

import pandas as pd

# Read dataset
df = pd.read_csv('https://codefinity-content-media.s3.eu-west-1.amazonaws.com/9c23bf60-276c-4989-a9d7-3091716b4507/datasets/sales_data_types.csv')

# Transform ‘Active’ column type to bool
df['Active'] = df['Active'].map({'Y': True, 'N': False})

Tout était clair ?

Comment pouvons-nous l'améliorer ?

Merci pour vos commentaires !

Section 1. Chapitre 5
import pandas as pd

# Read dataset
df = pd.read_csv('https://codefinity-content-media.s3.eu-west-1.amazonaws.com/9c23bf60-276c-4989-a9d7-3091716b4507/datasets/sales_data_types.csv')

# Transform ‘Active’ column type to bool
df['Active'] = df['Active'].___({'Y': ___, 'N': ___})

Demandez à l'IA

expand
ChatGPT

Posez n'importe quelle question ou essayez l'une des questions suggérées pour commencer notre discussion

some-alt