我如何一次为许多列删除字符串中的第一个字符?



我有6列是对象($19.99,$25.99等),我想把它们变成浮点数(19.99,25.99等)。我必须做的第一件事是删除所有这些列的第一个字符。我可以这样做。

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:]

我想知道是否有一种方法可以同时完成它们。我尝试了这个,但它没有工作,我得到了错误,"AttributeError: 'DataFrame'对象没有属性'str'"

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

试试这个:

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

试试这个:

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

最新更新