python - pandas.dataframe.fillna : NotImplementedError

标签 python pandas dataframe

我想使用 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 文件(实际上我想对多个 .csv 文件执行此操作)转换为更合适的格式。然后我想使用 fillna 命令沿着列轴填充缺失的数据。

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

最佳答案

使用bfillffillaxis=1:

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

部分问题在于 inplace=True 和链接方法。 inplace=True 返回一个空对象,因此没有任何东西可以调用链式方法。第二部分是 fillna(method='ffill') 可以缩短为 ffill()

关于python - pandas.dataframe.fillna : NotImplementedError,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51064157/

相关文章:

python 将一列的值与条件相加

python - 在不迭代的情况下向量化 Pandas DataFrame 上的乘法和字典映射?

python - Apache 上的 Django 网站,wsgi 失败

python - 在 Python 中绘制不规则间隔的 RGB 图像

python - 如何找到二进制数中连续1的组数

python - 值错误: unknown type object pandas eval for n rows => 100

scala - Scala 中 Select 语句中的 Math.abs 函数

Python:更改路径的部分(单个目录名称)

python - Pandas 重命名: change values of index for a specific column only

python - 使用 pandas 从数据框中删除空间