无法将字符串转换为浮点数:'5,994.98'

问题描述 投票:0回答:1

请查看图片;

您可以在这里看到错误和带有头文件的代码

  1. (https://i.stack.imgur.com/J2MBb.png)]
  2. (https://i.stack.imgur.com/XLF8e.png)]
  3. (https://i.stack.imgur.com/Zoouz.png)
  4. Desired Output

矩张量反转错误:无法将数组数据从 dtype('O') 转换为 dtype('float64')

我正在尝试为我的数据创建一个头文件并将其用于矩张量反演。

但是它会抛出错误;

TypeError:无法根据规则“安全”将数组数据从 dtype('O') 转换为 dtype('float64') 在处理上述异常的过程中,又出现了一个异常: ValueError:无法将字符串转换为浮点数:'5,994.98'

# Create headers
headers = dict(datetime=df["origin"][0],
               longitude=df["lon"][0],
               latitude=df["lat"][0],
               depth=",".join([ "%.4f"%d for d in depths]),
               path_to_data=event_dir,
               path_to_green=green_dir,
               green="herrmann",
               components="ZRT",
               degree=5,
               weight="distance",
               plot=0,
               correlate=0,
              )

# Add station table
pd.options.display.float_format = "{:,.2f}".format
frame = {"station": station_df[["network","station","location"]].apply(lambda x: ".".join(x),axis=1)}
df_out = pd.DataFrame(frame)
df_out[["distance","azimuth"]] = station_df[["distance","azimuth"]]
df_out["ts"] = int(30)
df_out["npts"] = int(150)
df_out["dt"] = dt
df_out["used"] = 1
df_out[["longitude","latitude"]] = station_df[["longitude","latitude"]]
#print(df_out.to_string(index=False))

# write
with open("mtinv.in","w") as f:
    for key, value in headers.items():
        f.write("{0:<15}{1}\n".format(key,value))
    f.write(df_out.to_string(index=False))
    
!cat mtinv.in
python pandas string dataframe data-conversion
1个回答
0
投票
 df["Column Name"] = pd.to_numeric(df["Column Name"].astype(str).str.replace(",","")) 

它将帮助您将 str 转换为数字。

© www.soinside.com 2019 - 2024. All rights reserved.