python - pandas 中分组数据框的 astype 方法失败

标签 python pandas

当我尝试将 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' 将非数字转换为 NaNs:

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/

相关文章:

python - 无法理解GaussianHMM()中这些参数之间的区别

javascript - 保存文件 Python - IOError 权限被拒绝

python - 如何在 CSV 文件中随机选择一定数量的行并保留其他行

python - 将 Python 字典打印为并排多列的 Pandas value_counts

python - 如何添加按键绑定(bind)?

python - 要求 cookie 会影响注册转化率吗?

python - Pandas 数据框中的平均标准

python - get_dummies 在 pandas 中的用法

java - 从 Python 程序中使用 -Xms 和 -Xmx 参数执行 jar 文件

python - pd.Serie 每行的平均值 "score"基于通过另一个分数系列映射的内容