【问题标题】:Why is Pandas replace() method not working?为什么 Pandas replace() 方法不起作用?
【发布时间】:2021-07-28 06:10:44
【问题描述】:

我正在尝试将我的 df 中的所有列替换为整数的价格,但是由于某种原因 replace() 方法不起作用:

df = pd.read_csv(f_name, dtype="string")
df = df[df.columns.dropna()]
df[cols_int] = df[cols_int].replace({"[\$]": "", "[,]": ""}, regex=True)
df[cols_int] = df[cols_int].astype(int)

错误:

ValueError: invalid literal for int() with base 10: '$499,000'

如果有任何帮助,我将不胜感激!

【问题讨论】:

  • 你需要使用替换来表示系列的字符串:df[cols_int].str.replace({"[\$]": "", "[,]": ""}, regex=True) -> 将.str.放在中间。
  • 不幸的是,我认为这不适用于多个列

标签: python python-3.x pandas dataframe replace


【解决方案1】:

这是dtype='string' 的错误:pandas-dev/pandas #35977 - BUG: replacement works for object but not string dtype

如果您使用dtype=strdtype='str' 加载,它应该可以正常工作:

df = pd.read_csv(f_name, dtype=str)
df = df[df.columns.dropna()]
df[cols_int] = df[cols_int].replace({"[\$]": "", "[,]": ""}, regex=True)
df[cols_int] = df[cols_int].astype(int)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-08-29
    • 1970-01-01
    • 2020-06-20
    • 2020-09-25
    • 2023-03-03
    • 1970-01-01
    • 2016-10-02
    相关资源
    最近更新 更多