您好, 欢迎来到 !    登录 | 注册 | | 设为首页 | 收藏本站

Python错误无法从空轴执行非空取

5b51 2022/1/14 8:21:38 python 字数 4336 阅读 538 来源 www.jb51.cc/python

我有一个超过40万行的pandas数据帧,现在我想计算每行的四分位数范围,但我的代码产生了以下错误: cannot do a non empty take from an empty axes 我的代码:def calIQR(x): x=x.dropna() return (np.percentile(x,75),np.percentil

概述

我有一个超过40万行的pandas数据帧,现在我想计算每行的四分位数范围,但我的代码产生了以下错误

cannot do a non empty take from an empty axes

我的代码

def calIQR(x):
    x=x.dropna()
    return (np.percentile(x,75),np.percentile(x,25))

df["count"]=df.iloc[:,2:64].apply(calIQR,axis=1)

我正在运行Python 2.7.13

我在网上搜索但仍然不知道为什么会出现这个错误.

2到64列数据集基本上看起来像这样:

dataset

在每一行中,都有一些NaN值,但我确信所有NaN都没有行.

因此需要在iloc之后添加dropna

np.random.seed(100)
df = pd.DataFrame(np.random.random((5,5)))
df.loc[3,[3,4]] = np.nan
df.loc[2] = np.nan
print (df)
         0         1         2         3         4
0  0.543405  0.278369  0.424518  0.844776  0.004719
1  0.121569  0.670749  0.825853  0.136707  0.575093
2       NaN       NaN       NaN       NaN       NaN
3  0.978624  0.811683  0.171941       NaN       NaN
4  0.431704  0.940030  0.817649  0.336112  0.175410
def calIQR(x):
    x = x.dropna()
    return (np.percentile(x,2:4].dropna(how='all').apply(calIQR,axis=1)
print (df)
          0         1         2         3         4  \
0  0.543405  0.278369  0.424518  0.844776  0.004719   
1  0.121569  0.670749  0.825853  0.136707  0.575093   
2       NaN       NaN       NaN       NaN       NaN   
3  0.978624  0.811683  0.171941       NaN       NaN   
4  0.431704  0.940030  0.817649  0.336112  0.175410   

                              count  
0  (0.739711496927,0.529582226142)  
1    (0.65356621375,0.30899313104)  
2                               NaN  
3  (0.171941012733,0.171941012733)  
4  (0.697265021613,0.456496307285)  

或者使用Series.quantile

 def calIQR(x):
    return (x.quantile(.75),x.quantile(.25))

#with real data change 2;4 to 2:64
df["count"]=df.iloc[:,2:4].apply(calIQR,axis=1)
print (df)
          0         1         2         3         4  \
0  0.543405  0.278369  0.424518  0.844776  0.004719   
1  0.121569  0.670749  0.825853  0.136707  0.575093   
2       NaN       NaN       NaN       NaN       NaN   
3  0.978624  0.811683  0.171941       NaN       NaN   
4  0.431704  0.940030  0.817649  0.336112  0.175410   

                                       count  
0   (0.7397114969272109,0.5295822261418257)  
1    (0.653566213750024,0.3089931310399766)  
2                                 (nan,nan)  
3   (0.1719410127325942,0.1719410127325942)  
4  (0.6972650216127702,0.45649630728485585)  

总结

以上是编程之家为你收集整理的Python错误无法从空轴执行非空取全部内容,希望文章能够帮你解决Python错误无法从空轴执行非空取所遇到的程序开发问题。


如果您也喜欢它,动动您的小指点个赞吧

除非注明,文章均由 laddyq.com 整理发布,欢迎转载。

转载请注明:
链接:http://laddyq.com
来源:laddyq.com
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。


联系我
置顶