当我尝试将 astype(float)
方法应用于 pandas 中的分组数据框时,出现以下错误。
ValueError: could not convert string to float:
你知道为什么我无法通过astype
方法将字符串转换为 float 吗?我该如何解决这个问题?
下面是我收到错误的代码和示例数据。
def group(self,agg_method):
df=self.df
grouped=df.groupby(['Tilt [deg]', 'Azimuth [deg]'],as_index=False)
groupdf=grouped.agg(agg_method)
print(groupdf['Azimuth [deg]'][0],len(groupdf['Azimuth [deg]'][0]))
groupdf['Azimuth [deg]']=groupdf['Azimuth [deg]'].astype(float) <- I get error here
示例数据
Tilt [deg] Azimuth [deg] Glass SHGC Area of Multiplied Openings [m2] \
0 90.0 124.48 0.57 1450.24
1 90.0 207.3 0.57 115.66
2 90.0 207.47 0.57 115.62
3 90.0 208.25 0.57 23.18
4 90.0 208.26 0.57 113.12
5 90.0 214.48 0.57 451.94
6 90.0 218.57 0.57 230.08
7 90.0 304.46 0.57 72.66
8 90.0 304.48 0.57 1827.53
9 90.0 34.48 0.57 917.29
最佳答案
我相信你需要to_numeric
使用参数 errors='coerce'
将非数字转换为 NaN
s:
groupdf['Azimuth [deg]']= pd.to_numeric(groupdf['Azimuth [deg]'], errors='coerce')
如果需要删除所有不可解析的列并且数据中没有 NaN 值,则可以使用 boolean indexing
并按 notnull
进行过滤:
groupdf = groupdf[pd.to_numeric(groupdf['Azimuth [deg]'], errors='coerce').notnull()]
在 pandas 的最新版本中,可以使用 0.21.0
Series.notna
:
groupdf = groupdf[pd.to_numeric(groupdf['Azimuth [deg]'], errors='coerce').notna()]
关于python - pandas 中分组数据框的 astype 方法失败,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47673455/