【问题标题】:Convert a pandas object into float将 pandas 对象转换为浮点数
【发布时间】:2021-08-11 18:22:27
【问题描述】:

我正在尝试编写一个可以读取 excel 文件的代码,找到哪一行对应于我想要的数据,然后保存该行的最后一个值。

我使用的代码是:

import pandas as ap
import numpy as np

#Read the Excel file
excel = ap.read_excel(r'EXAMPLE')

#Columns and rows selections
tec_data = excel.iloc[0::, 0:6]

#creating a numpy array with the table
np_array = tec_data.to_numpy()

#Found the line that corresponds to the pretended simulation data
found_tec_line = np.argwhere((month==np_array[:,0]) & (hour==np_array[:,1]) & (azimuth==np_array[:,2]) & (elevation==np_array[:,3]) & (height==np_array[:,4]))

#Save TEC
tec = np_array[found_tec_line,5]

所以,在这个阶段,我有一个数组([['27.8 * 10 * * 15']],dtype=object) 我只想将 27.89* 10* * 15 保存为浮点数,但我不知道该怎么做。 我使用了 tec = tec.astype(float),但它说“无法将字符串转换为浮点数:'27.89 * 10* * 15'”

注意:代码中的数字和*之间没有空格,我这里介绍空格只是因为自动加粗

【问题讨论】:

  • 您能否在示例中显示您希望输出的样子。它在excel中吗?还是回到数据框中?也不清楚你想从星号中得到什么
  • 我只想从 excel 中获取该特定值,然后在其他脚本上使用它(作为浮点数)

标签: python python-3.x pandas dataframe numpy-ndarray


【解决方案1】:
import pandas as pd

tec = np_array[found_tec_line,5]
tec=pd.eval(tec)

通过Dataframe()方法和apply()方法试试:

tec = np_array[found_tec_line,5]

tec=pd.Dataframe(tec).apply(pd.eval).values

【讨论】:

  • 谢谢!我在 eval(tec) 之后添加了一个 tec =tec.astype(float) 并且已经做了我想要的,将值保存为 float。
猜你喜欢
  • 1970-01-01
  • 2021-05-25
  • 2021-05-24
  • 2021-06-18
  • 1970-01-01
  • 2021-06-24
  • 2021-12-18
  • 1970-01-01
  • 2022-11-21
相关资源
最近更新 更多