python - 如何一次删除多列字符串中的第一个字符?

标签 python python-3.x pandas dataframe

我有 6 列对象($19.99、$25.99 等),我想将它们转换为 float (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:]

关于python - 如何一次删除多列字符串中的第一个字符?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66553953/

相关文章:

python - 获取两个坐标之间的距离时出错

python - 使用系列数据减去 Dataframe

python - 运行 python 文件

python - 使用 lxml 在另一个元素之后追加元素

python - 使用 alphabeta TicTacToe 找到最佳着法

python - 从 OrderedDict : preserving columns order 列表构建 Pandas DataFrame

python - 如何对 pandas 数据框中的字母数字列进行排序

python - 如何从字典列表中删除重复的字典对象

python - 高效算法perl或python

python - 使用 python : openpyxl or any other library 读取 excel 表中单元格的颜色