这是基本问题 - 数字被格式化为带有逗号而不是小数的字符串。我需要将列转换为数字数据。
vals = [
["1200,05", "2300,0", "45500", "1900,88"],
["2200,05", "4300,0", "65500", "3900,88"],
["100,95", "100,10", "3500", "900,9"]]
cols= ['system_sales', 'lounge_sales', 'delivery_sales', 'bar_sales']
df = pd.DataFrame(vals, columns=cols)
for col in cols:
df[col] = df[col].str.replace(',', ".", regex=False).astype(float)
print(df)
循环工作得很好,就像我的本地脚本中的许多变体一样,但是当我将相同的 csv 上传到远程服务器并执行相同的代码时,我得到了提升 attributeError(“只能使用带有字符串值的 .str 访问器!”)
我已经检查了远程脚本,以确保在尝试转换之前没有进行其他预处理 - 这些列是对象数据类型。
有没有人遇到过类似的情况,远程环境/Python解释器可能会对数据强加一些东西?
谢谢菲
ps 我尝试了很多变体,即
df[col] = pd.to_numeric(df[col].str.replace(',', repl='.', regex=True), errors='coerce').fillna(0)
df[col] = df[col].str.replace(',', '.', regex=False).astype(float)
# this stopped the error in the loop but obviously I have satisfied the key need
df[col] = df[col].str.replace(',', '.', regex=False)
我在内部发布了该问题,并收到了回复,详细说明在其环境中使用 .str 访问器是一个已知的错误/问题,需要解决方法。模组我们可以关闭这篇文章了。
谢谢@Nick 和@juanpa.arrivilillaga