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
-
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.
-
-
Apply the
rmv_rpl
function to the'Weekly_Sales'
column using the.apply()
method and convert it to thefloat
data type.
Lösning
99
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
# 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?
Tack för dina kommentarer!
Avsnitt 2. Kapitel 2
99
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
# 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
Fråga vad du vill eller prova någon av de föreslagna frågorna för att starta vårt samtal