鱼C论坛

 找回密码
 立即注册
查看: 4066|回复: 1

多个dataframe对象对应位置数据相加求平均数问题

[复制链接]
发表于 2017-12-9 21:38:31 | 显示全部楼层 |阅读模式

马上注册,结交更多好友,享用更多功能^_^

您需要 登录 才可以下载或查看,没有账号?立即注册

x
本帖最后由 Phoebe_Ma 于 2017-12-9 21:53 编辑

求教大神们~我想将一个文件夹中多个CSV文件(文件中有np.nan)中相应位置数据相加求平均数(求平均值时,遇到np.nan不能直接用数据总和除以所有数据个数,而应除以有数据的,不把算到数据数量里),程序写出来了~但是有问题~看不出问题出在哪里~程序如下:
def allelemeandata(folderpath):
    try:
        filelist=os.listdir(folderpath)
        for i in range(len(filelist)):
            filelist[i]=folderpath+'/'+filelist[i]
        dff=pd.read_csv(filelist[0],index_col=0)
        nindex=dff.index
        ncol=dff.columns
        newdf = pd.DataFrame(np.zeros(8760*5).reshape((8760,5)),index=nindex,columns=ncol)
        newdf.index.name=dff.index.name
        newdf.columns.name=dff.columns.name
        for i in range(len(filelist)):
            df=pd.read_csv(filelist[i],index_col=0)
                       for col in df.columns:
                for indx in df.index:
                    if df[col][indx]==np.nan:
                        df[col][indx]=0
                        newdf[col][indx]=newdf[col][indx]
                    else:
                        newdf[col][indx] = (newdf[col][indx]+df[col][indx])/2
        if os.path.exists(path + '/mean'):
            newpath = path + '/mean/'+'mean.csv'
        else:
            os.mkdir(path + '/mean')
            newpath = path + '/mean/'+'mean.csv'
        newdf.to_csv(newpath)
    except Exception:
        print('traceback.format_exc():\n %s' % traceback.format_exc())
程序显示错误如下:
traceback.format_exc():
Traceback (most recent call last):
  File "D:\Datapreprocessing\DataProcess.py", line 399, in allelemeandata
    newdf[col][indx] = (newdf[col][indx]+df[col][indx])/2
  File "C:\Anaconda3\lib\site-packages\pandas\core\series.py", line 623, in __getitem__
    result = self.index.get_value(self, key)
  File "C:\Anaconda3\lib\site-packages\pandas\core\indexes\base.py", line 2557, in get_value
    tz=getattr(series.dtype, 'tz', None))
  File "pandas/_libs/index.pyx", line 83, in pandas._libs.index.IndexEngine.get_value
  File "pandas/_libs/index.pyx", line 91, in pandas._libs.index.IndexEngine.get_value
  File "pandas/_libs/index.pyx", line 139, in pandas._libs.index.IndexEngine.get_loc
  File "pandas/_libs/hashtable_class_helper.pxi", line 811, in pandas._libs.hashtable.Int64HashTable.get_item
  File "pandas/_libs/hashtable_class_helper.pxi", line 817, in pandas._libs.hashtable.Int64HashTable.get_item
KeyError: 20
小甲鱼最新课程 -> https://ilovefishc.com
回复

使用道具 举报

 楼主| 发表于 2017-12-9 21:40:04 | 显示全部楼层
本帖最后由 Phoebe_Ma 于 2017-12-9 21:53 编辑

求教大神~真的想不出原因了呀~
小甲鱼最新课程 -> https://ilovefishc.com
回复 支持 反对

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

小黑屋|手机版|Archiver|鱼C工作室 ( 粤ICP备18085999号-1 | 粤公网安备 44051102000585号)

GMT+8, 2025-12-26 10:10

Powered by Discuz! X3.4

© 2001-2023 Discuz! Team.

快速回复 返回顶部 返回列表