龙空技术网

Python报错 字典keys value长度不一致创建DataFrame失败

之乎者矣 135

前言:

今天大家对“pythonfromkeys”大约比较关心,同学们都需要知道一些“pythonfromkeys”的相关文章。那么小编也在网上搜集了一些对于“pythonfromkeys””的相关内容,希望姐妹们能喜欢,你们快快来学习一下吧!

import  pandas as pdimport jsonimport  pymongoclient = pymongo.MongoClient('xxxxxxxxxxxxxx')print('连接成功!')db=client['xx']table=db['xxx']info_trim={}for i in table.find({}):    print(i)    print('-'*70)    print(i.keys())    k1 = i['11']    k2=i['22']    k3 = i['33']    k4 = i['44']    k5 = i['55']    info_trim.setdefault('66',[]).append(k1)    info_trim.setdefault('77', []).append(k2)    info_trim.setdefault('88', []).append(k3)    info_trim.setdefault('99', []).append(k4)    info_trim.setdefault('10', []).append(k5)    cols_1=list(i.keys())[9:]    print(cols_1)    for c1 in cols_1:        # print(c1)        cols_2 = list(i[c1].keys())        for c2 in cols_2:            try:                cols_name=c1.replace(" ","").lower()+'_'+c2.replace(" ","").lower()                val=i[c1][c2]                info_trim.setdefault(cols_name,[]).append(val)                print(cols_name,val)            except:                continue        # print(cols_2)print(info_trim)info_trim=pd.DataFrame.from_dict(info_trim,orient='index')info_trim.to_excel("xxxxxxxxxxxxxxxxxxxxxxxxx")print(info_trim)

创建DataFrame 用from_dict、orient='index' 缺失的用None补充

info_trim=pd.DataFrame.from_dict(info_trim,orient='index')

标签: #pythonfromkeys