How do I drop the first character in a string for many columns at once?

Viewed 41

I have 6 columns that are objects ($19.99, $25.99, etc.) that I want to turn into floats (19.99, 25.99, etc.). The first thing I must do is drop the first character for all of these columns. I was able to do it doing this.

df['Subtotal_'] = df['Subtotal'].str[1:]
df['Shipping Charge_'] = df['Shipping Charge_'].str[1:]
df['Tax Before Promotions_'] = df['Tax Before Promotions_'].str[1:]
df['Total Promotions_'] = df['Total Promotions_'].str[1:]
df['Tax Charged_'] = df['Tax Charged_'].str[1:]
df['Total Charged_'] = df['Total Charged_'].str[1:]

I was wondering if there was a way to do them all at once. I tried this but it didn't work and I got the error, "AttributeError: 'DataFrame' object has no attribute 'str'".

df[['Subtotal_', 'Shipping Charge_', 'Tax Before Promotions_',
    'Total Promotions_', 'Tax Charged_', 'Total Charged_']] = df.loc[:, 'Subtotal':'Total Charged'].str[1:]
2 Answers

Try this:

cols = ('Subtotal_', 'Shipping Charge_', 'Tax Before Promotions_', 'Total Promotions_', 'Tax Charged_', 'Total Charged_')
for col in cols:
    df[col] = df[col].str[1:]

Try this:

df.loc[:, list_of_the_columns_to_change] = df[same_list].replace('^\$', '', regex=True)
Related