Notice: This page requires JavaScript to function properly.
Please enable JavaScript in your browser settings or update your browser.
Lära Removing and Replacing | Preprocessing Data: Part II
Analyzing and Visualizing Real-World Data

book
Removing and Replacing

As mentioned previously, there are two ways to perform removing or replacing operations. Since we used the .str accessor two chapters ago, let's use a lambda function this time.

Uppgift

Swipe to start coding

  1. Define a lambda function with a single argument x that will:

    • Remove the '$' characters starting from the left (using the .lstrip() method);

    • Replace all blank spaces (' ') with empty strings ('') (using the .replace() method);

    • Assign the function to the rmv_rpl variable.

  2. Apply the rmv_rpl function to the 'Weekly_Sales' column using the .apply() method and convert it to the float data type.

Lösning

# Load the library
import pandas as pd

# Read the data
df = pd.read_csv('https://codefinity-content-media.s3.eu-west-1.amazonaws.com/72be5dde-f3e6-4c40-8881-e1d97ae31287/shops_data2.csv')

# Define a lambda function
rmv_rpl = lambda x: x.lstrip('$').replace(' ', '')

# Convert the 'Weekly_Sales' column into numerical
df['Weekly_Sales'] = df['Weekly_Sales'].apply(rmv_rpl).astype(float)

# Display the first row of dataframe and dtypes
print(df.head(1))
print(df.dtypes)

Var allt tydligt?

Hur kan vi förbättra det?

Tack för dina kommentarer!

Avsnitt 2. Kapitel 2
# Load the library
import pandas as pd

# Read the data
df = pd.read_csv('https://codefinity-content-media.s3.eu-west-1.amazonaws.com/72be5dde-f3e6-4c40-8881-e1d97ae31287/shops_data2.csv')

# Define a lambda function
rmv_rpl = lambda ___: x.___('___').___(___, ___)

# Convert the 'Weekly_Sales' column into numerical
df['Weekly_Sales'] = df['___'].___(___).___(___)

# Display the first row of dataframe and dtypes
print(df.head(1))
print(df.dtypes)

Fråga AI

expand
ChatGPT

Fråga vad du vill eller prova någon av de föreslagna frågorna för att starta vårt samtal

some-alt