Hri*_*kar 2 python dataframe pandas
我想使用 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
Run Code Online (Sandbox Code Playgroud)
错误:
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
Run Code Online (Sandbox Code Playgroud)
编写代码的动机:
我本质上想将 .csv 文件读入由该表的不同子集组成的多个数据帧(因此我使用了所有循环),以便重新排列和分割 .csv 文件(实际上我想这样做多个 .csv 文件)转换为更合适的格式。然后我想使用 fillna 命令沿列轴填充缺失的数据。
该代码的结构是为了读取多个 .csv 文件,因此具有诸如“df=[]”和“for 循环”之类的不必要的命令,但为了简化目的,我首先尝试了此代码只是为了确保我收到此错误。请随时询问有关此错误的更多信息。谢谢!
dfs = dfs.bfill(axis=1).ffill(axis=1)
Run Code Online (Sandbox Code Playgroud)
部分问题在于inplace=True和 链接方法。inplace=True返回一个空对象,因此没有任何东西可以调用链式方法。第二部分fillna(method='ffill')可以缩短为ffill().
| 归档时间: |
|
| 查看次数: |
2508 次 |
| 最近记录: |