【问题标题】:divide the values from pandas df column by number将 pandas df 列中的值除以数字
【发布时间】:2020-09-01 15:22:16
【问题描述】:

我需要将一列的每个值除以 25。下面是我的代码:

df['Amount'] = df['Amount'].div(25)

我收到一个错误:TypeError: unsupported operand type(s) for /: 'str' and 'int' 然后我尝试使用以下代码将 Object 数据类型转换为 int:

df["Amount"] = df["Amount"].astype(str).astype(int)

错误信息:ValueError: invalid literal for int() with base 10: '0.0'

【问题讨论】:

  • 试试df["Amount"].astype(float).div(25)
  • pd.to_numeric 是将列转换为数字 dtype 的灵活方法

标签: python pandas dataframe divide


【解决方案1】:

你可以试试pd.to_numeric函数,如果你想指定它是一个float列,你可以试试downcast参数,虽然如果你不添加它很可能没问题。

df["Amount"] = pd.to_numeric(df["Amount"], downcast='float')

【讨论】:

    【解决方案2】:

    你可以试试这个:

    df["Amount"] = df["Amount"]/25
    print(df)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2022-11-29
      • 2018-11-11
      • 2021-11-03
      • 2021-06-09
      • 1970-01-01
      • 2022-11-26
      • 2020-10-14
      • 1970-01-01
      相关资源
      最近更新 更多