首页 > 解决方案 > pandas.dataframe.fillna: NotImplementedError

问题描述

我想使用 pandas 中的 fillna 命令来估算数据框。这是我的代码片段:

import glob
import pandas as pd
files=glob.glob("IN.201*.csv")
i=0
n=1    
#the while loops are for reading and writing different subsets of the table into 
#different .txt files:
while i<15:
   j=0
   while j<7:
    dfs=[]
    m=1
   #for loop over only one file for testing:
       for file in files[:1]:
        z=i+1
        #reading subset of the dataframe:
        k=float(68.109375)+float(1.953125)*i
        k1=float(68.109375)+float(1.953125)*z
        l=float(8.0)+float(4)*j
        l1=float(8.0)+float(4)*(j+1)
        df=pd.read_csv(path+file).query( '@k <= lon < @k1 and @l < lat <= @l1')[['lon','lat','country','avg']]
        #renaming columns in df: 
        df.rename(columns={"avg":"Day"+str(m)}, inplace=True)
        #print(df)
        m=m+1
        dfs.append(df)
  #imputation: 
    df_final=dfs[0].fillna(method='bfill', axis='columns', inplace=True).fillna(method='ffill', axis=1, inplace=True)
  #writing to a txt file:
    with open('Region_'+str(n), 'w+') as f:
        df_final.to_csv(f)

    n=n+1
    j=j+1
   i=i+1

错误:

 Traceback (most recent call last):
 File "imputation_test.py", line 42, in <module>
 df_final=dfs[0].fillna(method='bfill', axis='columns', inplace=True).fillna(
 method='ffill', axis=1, inplace=True)
 File "C:\Users\DELL\AppData\Local\Programs\Python\Python36\lib\site- 
 packages\p
 andas\core\frame.py", line 3787, in fillna
 downcast=downcast, **kwargs)
 File "C:\Users\DELL\AppData\Local\Programs\Python\Python36\lib\site-packages\pandas\core\generic.py", line 5359, in fillna
raise NotImplementedError()
 NotImplementedError

代码的动机:

我本质上想将 .csv 文件读入由该表的不同子集组成的多个数据帧(因此我使用了所有循环),以便重新排列和拆分 .csv 文件/s(实际上我想这样做多个 .csv 文件)转换为更合适的格式。然后我想沿列轴使用 fillna 命令填充缺失的数据。

该代码的结构是为了读取多个 .csv 文件,因此具有不必要的命令,例如“df=[]”和“for 循环”,但为了简化起见,我首先尝试了这段代码,以确保我得到了这个错误. 随时询问有关此错误的更多信息。谢谢!

标签: pythonpandasdataframe

解决方案


使用bfill和:ffill_axis=1

dfs = dfs.bfill(axis=1).ffill(axis=1)

问题的一部分是inplace=True和链接方法。inplace=True返回一个空对象,所以没有什么可以调用链式方法。第二部分fillna(method='ffill')可以缩短为 just ffill()


推荐阅读