parseCreditPdf.py0525 146 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028
  1. #coding=utf-8
  2. import shutil
  3. import pdfplumber
  4. import pandas as pd
  5. import numpy as np;
  6. import sys
  7. import os
  8. import traceback
  9. from prp import PrpCrypt
  10. #指标相关
  11. import loanIndexParser as lip;
  12. import payRcdIndexParser as prp;
  13. import creditCardIndexParser as cip
  14. import queryInfoIndexParser as qip
  15. import requests
  16. import utils;
  17. import time;
  18. import consts;
  19. import math
  20. import dfParser;
  21. import gc
  22. from dbController import DbController
  23. from ini_op import Config;
  24. base_dir = os.path.dirname(os.path.abspath(__file__))
  25. config = Config(base_dir+"/config.ini");
  26. #连接数据库
  27. dbController = DbController();
  28. pd.set_option('mode.chained_assignment', None)
  29. import log
  30. logger = log.logger
  31. # 查询信息
  32. dfMap = {};
  33. allHeaders = [] # 所有表头
  34. queryInfoDf = pd.DataFrame();
  35. queryInfoDf_header = ["被查询者姓名", "被查询者证件类型", "被查询者证件号码", "查询机构", "查询原因"];
  36. dfMap["queryInfoDf"] = {"df": queryInfoDf, "nextDf": None};
  37. allHeaders.append(queryInfoDf_header);
  38. # 身份信息
  39. identityDf = pd.DataFrame();
  40. identity_header = ['性别', '出生日期', '婚姻状况', '学历', '学位', '就业状况', '国籍', '电子邮箱']
  41. addressDf = pd.DataFrame(); # 通讯地址
  42. dfMap["identityDf"] = {"df": identityDf, "nextDf": None, "mobiles": None};
  43. allHeaders.append(identity_header);
  44. # 配偶信息
  45. mateDf = pd.DataFrame();
  46. mateDf_header = ['姓名', '证件类型', '证件号码', '工作单位', '联系电话']
  47. dfMap["mateDf"] = {"df": mateDf, "nextDf": None};
  48. allHeaders.append(mateDf_header);
  49. # 居住信息====暂时该信息没有用到先不解析
  50. liveInfoDf = pd.DataFrame();
  51. liveInfoDf_header = ['编号', '居住地址', '住宅电话', '居住状况', '信息更新日期']
  52. dfMap["liveInfoDf"] = {"df": liveInfoDf, "nextDf": None};
  53. allHeaders.append(liveInfoDf_header);
  54. # 职业信息
  55. occupationDf = pd.DataFrame();
  56. occupationInfo_header = ['编号', '工作单位', '单位性质', '单位地址', '单位电话']
  57. occupationInfo_header1 = ['编号', '职业', '行业', '职务', '职称', '进入本单位年份', '信息更新日期']
  58. dfMap["occupationDf"] = ({"df": occupationDf, "nextDf": None});
  59. # allHeaders.append(occupationInfo_header1);
  60. allHeaders.append(occupationInfo_header);
  61. # 上次查询记录
  62. preQueryRcd_header0 = ['上一次查询记录']
  63. allHeaders.append(preQueryRcd_header0);
  64. # 查询记录概要
  65. # queryInfoBriefDf = pd.DataFrame();
  66. # queryInfoBrief_header0 = ['最近1个月内的查询机构数', '最近1个月内的查询次数', '最近2年内的查询次数']
  67. # queryInfoBrief_header1 = ['贷款审批', '信用卡审批', '贷款审批', '信用卡\n审批', '本人查询', '贷后管理', '担保资格\n审查', '特约商户\n实名审查']
  68. # dfMap["queryInfoBriefDf"] = ({"df": queryInfoBriefDf, "nextDf": None});
  69. # allHeaders.append(queryInfoBrief_header0);
  70. # allHeaders.append(queryInfoBrief_header1);
  71. # 信贷交易信息提示
  72. loanTradeInfoDf = pd.DataFrame();
  73. loanTradeInfo_header = ['业务类型', '账户数', '首笔业务发放月份'];
  74. dfMap["loanTradeInfoDf"] = ({"df": loanTradeInfoDf, "nextDf": None});
  75. allHeaders.append(loanTradeInfo_header)
  76. # 信贷交易违约信息概要
  77. # 被追偿信息汇总 资产处置和垫款业务
  78. recoveryInfoSumDf = pd.DataFrame();
  79. recoveryInfoSumDf_header = ['业务种类', '账户数', '余额'];
  80. dfMap["recoveryInfoSumDf"] = ({"df": recoveryInfoSumDf, "nextDf": None});
  81. allHeaders.append(recoveryInfoSumDf_header)
  82. # 呆账信息汇总
  83. badDebtsInfoSumDf = pd.DataFrame();
  84. badDebtsInfoSumDf_header = ['账户数', '余额']; # 被追偿信息汇总
  85. dfMap["badDebtsInfoSumDf"] = ({"df": badDebtsInfoSumDf, "nextDf": None});
  86. allHeaders.append(badDebtsInfoSumDf_header)
  87. # 逾期透资信息汇总
  88. overdueInfoSumDf = pd.DataFrame();
  89. overdueInfoSumDf_header = ['账户类型', '账户数', '月份数', '单月最高逾期/透支总额', '最长逾期/透支月数']
  90. dfMap["overdueInfoSumDf"] = ({"df": overdueInfoSumDf, "nextDf": None});
  91. allHeaders.append(overdueInfoSumDf_header)
  92. # 非循环贷账户信息汇总
  93. loanAccountInfoSumDf = pd.DataFrame();
  94. loanAccountInfoSumDf_header0 = ['非循环贷账户信息汇总']
  95. loanAccountInfoSumDf_header1 = ['管理机构数', '账户数', '授信总额', '余额', '最近6个月平均应还款']
  96. dfMap["loanAccountInfoSumDf"] = ({"df": loanAccountInfoSumDf, "nextDf": None});
  97. allHeaders.append(loanAccountInfoSumDf_header0)
  98. allHeaders.append(loanAccountInfoSumDf_header1)
  99. # 循环额度下分账户信息汇总
  100. cycleCreditAccountInfoSumDf = pd.DataFrame();
  101. cycleCreditAccountInfoSumDf_header0 = ['循环额度下分账户信息汇总']
  102. cycleCreditAccountInfoSumDf_header1 = ['管理机构数', '账户数', '授信总额', '余额', '最近6个月平均应还款'],
  103. dfMap["cycleCreditAccountInfoSumDf"] = ({"df": cycleCreditAccountInfoSumDf, "nextDf": None});
  104. allHeaders.append(cycleCreditAccountInfoSumDf_header0)
  105. allHeaders.append(cycleCreditAccountInfoSumDf_header1)
  106. # 循环贷账户信息汇总
  107. cycleLoanAccountInfoSumDf = pd.DataFrame();
  108. cycleLoanAccountInfoSumDf_header0 = ['循环贷账户信息汇总']
  109. cycleLoanAccountInfoSumDf_header1 = ['管理机构数', '账户数', '授信总额', '余额', '最近6个月平均应还款']
  110. dfMap["cycleLoanAccountInfoSumDf"] = ({"df": cycleLoanAccountInfoSumDf, "nextDf": None});
  111. allHeaders.append(cycleLoanAccountInfoSumDf_header0)
  112. allHeaders.append(cycleLoanAccountInfoSumDf_header1)
  113. # 贷记卡账户信息汇总
  114. creditCardInfoSumDf = pd.DataFrame();
  115. creditCardInfoSumDf_header0 = ['贷记卡账户信息汇总']
  116. creditCardInfoSumDf_header1 = ['发卡机构数', '账户数', '授信总额', '单家机构最高\n授信额', '单家机构最低\n授信额', '已用额度', '最近6个月平\n均使用额度']
  117. dfMap["creditCardInfoSumDf"] = ({"df": creditCardInfoSumDf, "nextDf": None});
  118. allHeaders.append(creditCardInfoSumDf_header0)
  119. allHeaders.append(creditCardInfoSumDf_header1)
  120. # 准贷记卡账户信息汇总
  121. creditCardInfoSumDfZ = pd.DataFrame();
  122. creditCardInfoSumDfZ_header0 = ['准贷记卡账户信息汇总']#'准贷记卡账户信息汇总'
  123. creditCardInfoSumDfZ_header1 = ['发卡机构数', '账户数', '授信总额', '单家机构最高\n授信额', '单家机构最低\n授信额', '透支余额', '最近6个月平\n均透支余额']
  124. dfMap["creditCardInfoSumDfZ"] = ({"df": creditCardInfoSumDfZ, "nextDf": None});
  125. allHeaders.append(creditCardInfoSumDfZ_header0)
  126. allHeaders.append(creditCardInfoSumDfZ_header1)
  127. #公共信息概要
  128. publicInfoBriefDf = pd.DataFrame();
  129. publicInfoBriefDf_header0 = ['公共信息汇总']
  130. dfMap["publicInfoBriefDf"] = ({"df": publicInfoBriefDf, "nextDf": None});
  131. allHeaders.append(publicInfoBriefDf_header0)
  132. #查询记录汇总
  133. queryRecordSumDf_header0=['最近1个月内的查询机构数', '最近1个月内的查询次数', '最近2年内的查询次数']
  134. queryRecordSumDf = pd.DataFrame();
  135. dfMap["queryRecordSumDf"] = ({"df": queryRecordSumDf, "nextDf": None});
  136. allHeaders.append(queryRecordSumDf_header0)
  137. # 非循环贷账户,循环额度下分账户
  138. # 循环贷账户
  139. loan_header = ['管理机构', '账户标识', '开立日期', '到期日期', '借款金额', '账户币种']
  140. loanDfs = [];
  141. dfMap["loanDfs"] = ({"dfs": loanDfs, "nextDf": []});
  142. allHeaders.append(loan_header)
  143. # 贷记卡账户
  144. creditCard_header = ['发卡机构', '账户标识', '开立日期', '账户授信额度', '共享授信额度', '币种', '业务种类', '担保方式']
  145. creditCardDfs = [];
  146. dfMap["creditCardDfs"] = ({"dfs": creditCardDfs, "nextDf": []});
  147. allHeaders.append(creditCard_header)
  148. # 准备贷记卡账户
  149. creditCardZ_header = ['发卡机构', '账户标识', '开立日期', '账户授信额度', '共享授信额度', '币种', '担保方式']
  150. creditCardDfsZ = [];
  151. dfMap["creditCardDfsZ"] = ({"dfs": creditCardDfsZ, "nextDf": []});
  152. allHeaders.append(creditCardZ_header)
  153. #
  154. # 相关还款责任信息汇总 未使用到
  155. # 信贷交易信息明细
  156. # 被追偿信息 未使用到
  157. recoveryInfoDfs_header = ['管理机构','业务种类','债权接收日期','债权金额','债权转移时的还款状态']
  158. recoveryInfoDfs = [];
  159. dfMap["recoveryInfoDfs"] = ({"dfs": recoveryInfoDfs, "nextDf": []});
  160. allHeaders.append(recoveryInfoDfs_header)
  161. # 公共信息明细
  162. # 强制执行记录
  163. forceExecRcdDfs_header = ['编号', '执行法院', '执行案由', '立案日期', '结案方式']
  164. forceExecRcdDfs = [];
  165. dfMap["forceExecRcdDfs"] = ({"dfs": forceExecRcdDfs, "nextDf": []});
  166. allHeaders.append(forceExecRcdDfs_header)
  167. # 查询记录
  168. queryRecordDetailDf_header = ['编号', '查询日期', '查询机构', '查询原因']
  169. dfMap["queryRecordDetailDf"] = ({"df": pd.DataFrame(), "nextDf": []});
  170. allHeaders.append(queryRecordDetailDf_header)
  171. #住房公积金参缴记录
  172. housingFundRcdDfs_header =['参缴地', '参缴日期', '初缴月份', '缴至月份', '缴费状态', '月缴存额', '个人缴存比例', '单位缴存比例']
  173. housingFundRcdDfs = []
  174. dfMap["housingFundRcdDfs"] = ({"dfs": housingFundRcdDfs, "nextDf": []});
  175. allHeaders.append(housingFundRcdDfs_header)
  176. repaymentSumDf_header0=['相关还款责任信息汇总']
  177. dfMap["repaymentSumDf"] = ({"df": pd.DataFrame(), "nextDf": None});
  178. allHeaders.append(repaymentSumDf_header0)
  179. # 处理分页思路
  180. # df估计得放到对象里面,然后存储下一个df,一个对象里包含key
  181. # 然后判断对象的df的完整性,如果不完整代表被分页了,把nextdf合并到当前的df
  182. # 针对可合并的列的场景
  183. # =======
  184. keyList = [] # 存储所有的df的key列表
  185. # pd.Series()
  186. # 检查数据是否带表头
  187. # 应该是每一页开头的一行和每个表头对比一次,确认是不是表头,或者表头有什么共同的规律也可以看下
  188. import timeit
  189. # 定义指标部分======================start
  190. reportTime = ""; # 报告时间
  191. # 被查询者姓名
  192. queryInfoName = "";
  193. queryInfoCardId = "" # 被查询者证件号码
  194. # 定义指标部分======================end
  195. # 被查询信息-基础信息
  196. # 报告时间
  197. # 被查询者姓名
  198. # 被查询者证件号码
  199. # 基础信息
  200. queryInfo = {"reportTime":"","queryInfoCardId":""}
  201. # 身份信息
  202. identity = {}
  203. # 配偶信息
  204. mate = {}
  205. # 信贷交易信息提示-信用提示
  206. loanTradeInfo = {'perHouseLoanAccount': 0, 'perBusHouseLoanAccount': 0, 'otherLoanAccount': 0, 'loanMonthMin': 0,
  207. 'creditCardMonthMin': 0, 'creditAccount': 0, 'creditAccountZ': 0}
  208. # 逾期及违约信息概要
  209. overdueBrief = {}
  210. # 逾期及透资信息汇总
  211. # 贷款逾期账户数 loanOverdueAccount
  212. # 贷款逾期月份数 loanOverdueMonth
  213. # 贷款单月最高逾期总额 loanCurMonthOverdueMaxTotal
  214. # 贷款最长逾期月数 loanMaxOverdueMonth
  215. overdueInfo = {"loanOverdueAccount": "", "loanOverdueMonth": "", "loanCurMonthOverdueMaxTotal": "",
  216. "loanMaxOverdueMonth": "",
  217. "creditCardOverdueAccount": "", "creditCardOverdueMonth": "", "creditCardCurMonthOverdueMaxTotal": "",
  218. "creditCardMaxOverdueMonth": ""}
  219. # 未结清贷款信息汇总
  220. # ['管理机构数', '账户数', '授信总额', '余额', '最近6个月平均应还款']
  221. loanAccountInfoSum = {"mgrOrgCount": 0, "account": 0, "creditTotalAmt": 0, "balance": 0, "last6AvgPayAmt": 0}
  222. # 未销户贷记卡发卡法人机构数
  223. # 未销户贷记卡发卡机构数
  224. # 未销户贷记卡账户数
  225. # 未销户贷记卡授信总额
  226. # 未销户贷记卡单家行最高授信额
  227. # 未销户贷记卡单家行最低授信额
  228. # 未销户贷记卡已用额度
  229. # 未销户贷记卡近6月平均使用额度
  230. # 未结清贷记卡信息汇总
  231. # ['发卡机构数', '账户数', '授信总额', '单家机构最高\n授信额', '单家机构最低\n授信额', '已用额度', '最近6个月平\n均使用额度']
  232. creditCardInfoSum = {"awardOrgCount": 0, "account": 0, "creditTotalAmt": 0, "perMaxCreditTotalAmt": 0,
  233. "perMinCreditTotalAmt": 0, "useAmt": 0, "last6AvgUseAmt": 0}
  234. # 信 贷 审 批 查 询 记 录 明 细
  235. queryRecordDetail = {"last1MonthQueryTimes": 0, "last3MothLoanApproveTimes": 0, "last3MonthQueryTimes": 0,
  236. "lastTimeLoanApproveMonth": 0}
  237. #最近一笔结清贷款的贷款金额 
  238. loanAccountInfo = {"lastSettleLoanAmt": 0}
  239. loanAccountDfs=[];#横向合并
  240. creditCardAccountDfs=[];#贷记卡账户合并
  241. creditCardAccountDfsZ=[];#准贷记卡账户合并
  242. recoveryInfoAccountDfs=[];#被追偿账户合并
  243. housingFundRcdAccountDfs=[];#公积金账户合并
  244. #============================指标定义区 start=============================
  245. #基本信息 拆分
  246. # basicInfoDf = pd.DataFrame(columns=consts.basicInfoHeader, index=[0])
  247. #身份信息
  248. identityInfoIndex = '身份信息'
  249. identityInfoDf = pd.DataFrame(columns=consts.identityInfoHeader,index=[identityInfoIndex])
  250. #配偶信息
  251. mateInfoIndex = '配偶信息'
  252. mateInfoDf = pd.DataFrame(columns=consts.mateInfoHeader,index=[mateInfoIndex])
  253. #居住信息
  254. liveInfoIndex = '居住信息'
  255. liveInfoDf = pd.DataFrame(columns=consts.liveInfoHeader,index=[liveInfoIndex])
  256. #职业信息
  257. occupationInfoIndex = '职业信息'
  258. occupationInfoDf = pd.DataFrame(columns=consts.occupationInfoHeader,index=[occupationInfoIndex])
  259. #信贷交易信息提示
  260. loanTradeInfoIndex = '信贷交易信息提示'
  261. briefInfoDf_loanTradeInfo = pd.DataFrame(columns=consts.briefInfoHeader_loanTradeInfo,index=[loanTradeInfoIndex])
  262. #被追偿信息汇总及呆账信息汇总
  263. recoveryInfoSumIndex = '信贷交易违约信息概要'
  264. briefInfoDf_recoveryInfoSum = pd.DataFrame(columns=consts.briefInfoHeader_recoveryInfo,index=[recoveryInfoSumIndex])
  265. #呆账信息汇总
  266. badDebtsInfoIndex = '呆账信息汇总'
  267. briefInfoDf_badDebtsInfoSum = pd.DataFrame(columns=consts.briefInfoHeader_badDebtsInfoSum,index=[badDebtsInfoIndex])
  268. #逾期(透支)信息汇总
  269. overdueInfoSumIndex='逾期(透支)信息汇总'
  270. briefInfoDf_overdueInfoSum = pd.DataFrame(columns=consts.briefInfoHeader_overdueInfoSum,index=[overdueInfoSumIndex])
  271. #信贷交易授信及负债信息概要
  272. loanTradeCreditInfoIndex='信贷交易授信及负债信息概要'
  273. briefInfoDf_loanTradeCreditInfo = pd.DataFrame(columns=consts.briefInfoHeader_loanTradeCreditInfo,index=[loanTradeCreditInfoIndex]).fillna(0.0)
  274. #公共信息概要
  275. publicInfoBriefIndex = '公共信息概要'
  276. publicInfoBriefDf = pd.DataFrame(columns=consts.publicInfoBriefHeader,index=[publicInfoBriefIndex])
  277. #查询记录汇总
  278. queryRecordSumIndex = '查询记录汇总'
  279. queryRecordSumDf = pd.DataFrame(columns=consts.queryRecordSumHeader,index=[queryRecordSumIndex])
  280. #信贷交易明细-被追偿信息
  281. recoveryInfoIndex='被追偿信息'
  282. creditTradeDetailDf_recoveryInfo = pd.DataFrame(columns=consts.creditTradeDetailHeader_recoveryInfo,index=[recoveryInfoIndex])
  283. #信贷交易明细-特殊交易
  284. specialTradeIndex='特殊交易'
  285. creditTradeDetailHeader_specialTrade = pd.DataFrame(columns=consts.creditTradeDetailHeader_specialTrade,index=[specialTradeIndex])
  286. #信贷交易明细
  287. #非循环贷账户
  288. loanInfoIndex='非循环贷账户'
  289. creditTradeDetailDf_loanAccountInfo = pd.DataFrame(columns=consts.creditTradeDetailHeader_loanAccountInfo,index=[loanInfoIndex])
  290. #循环额度下分账户
  291. cycleCreditAccountInfoIndex='循环额度下分账户'
  292. creditTradeDetailDf_cycleCreditAccountInfo = pd.DataFrame(columns=consts.creditTradeDetailHeader_cycleCreditAccountInfo,index=[cycleCreditAccountInfoIndex])
  293. #循环贷账户
  294. cycleLoanAccountInfoIndex='循环贷账户'
  295. creditTradeDetailDf_cycleLoanAccountInfo = pd.DataFrame(columns=consts.creditTradeDetailHeader_cycleLoanAccountInfo,index=[cycleLoanAccountInfoIndex])
  296. #贷款信息
  297. loanAccountInfoIndex='贷款信息'
  298. loanAccountInfoDf = pd.DataFrame(columns=consts.loanAccountInfoHeader,index=[loanAccountInfoIndex])
  299. #贷记卡信息
  300. creditCardAccountInfoIndex = '贷记卡账户'
  301. creditCardAccountInfoDf = pd.DataFrame(columns=consts.creditCardAccountInfoHeader,index=[creditCardAccountInfoIndex])
  302. #准贷记卡
  303. creditCardAccountInfoIndexZ = '准贷记卡账户'
  304. creditCardAccountInfoDfZ = pd.DataFrame(columns=consts.creditCardAccountInfoHeaderZ,index=[creditCardAccountInfoIndexZ])
  305. useRateIndex = '使用率'
  306. useRateDf = pd.DataFrame(columns=consts.creditTradeDetailHeader_useRate,index=[useRateIndex])
  307. openAccountIndex = '开户数'
  308. openAccountDf = pd.DataFrame(columns=consts.creditTradeDetailHeader_openAccount,index=[openAccountIndex])
  309. payRcdStatusIndex = '24期还款状态'
  310. payRcdStatusDf = pd.DataFrame(columns=consts.creditTradeDetailHeader_payRcdStatus,index=[payRcdStatusIndex])
  311. #查询记录明细指标
  312. queryRecordDetailIndex = '信贷审批查询记录明细'
  313. queryRecordDetailDf = pd.DataFrame(columns=consts.queryRecordDetailHeader,index=[queryRecordDetailIndex])
  314. #住房公积金
  315. housingFundRcdIndex = '住房公积金参缴记录'
  316. housingFundRcdDf = pd.DataFrame(columns=consts.housingFundRcdHeader,index=[housingFundRcdIndex])
  317. #============================指标定义区 end=============================
  318. # 解析被查询信息指标
  319. def parseQueryInfo(dfObj):
  320. df = dfObj["df"];
  321. reportTime = df.loc[0, :][3]
  322. reportTime = reportTime.split(":")[1]
  323. reportTime = reportTime.replace(".", "-"); # 报告时间
  324. queryInfo["reportTime"] = reportTime
  325. row = df.loc[2, :]
  326. queryInfo["queryInfoName"] = row[0]; # 被查询者姓名
  327. # basicInfoDf.loc[0, '姓名'] = row[0]
  328. queryInfo["queryInfoCardId"] = row[2].replace("\n", ""); # 被查询者证件号码
  329. # basicInfoDf.loc[0, '身份证'] = row[2].replace("\n", "")
  330. # 婚姻状况
  331. # 学历
  332. # 单位电话
  333. # 住宅电话
  334. # 通讯地址
  335. def parseIdentity(dfObj):
  336. df = dfObj["df"];
  337. if not df.empty:
  338. row1 = df.loc[1, :].dropna().reset_index(drop=True)
  339. # identity["marital"] = row1[3] # 婚姻状况
  340. # identity["education"] = row1[4] # 学历
  341. # identity["commAddress"] = row1[9].replace("\n", ""); # 通讯地址
  342. identityInfoDf.loc[identityInfoIndex, '性别'] = row1[0]
  343. identityInfoDf.loc[identityInfoIndex, '出生日期'] = dfParser.formatDate(row1[1])[0:7]
  344. identityInfoDf.loc[identityInfoIndex, '国籍'] = row1[6]
  345. identityInfoDf.loc[identityInfoIndex, '户籍地址'] = row1[9].replace("\n", "")
  346. identityInfoDf.loc[identityInfoIndex, '婚姻状况'] = row1[2]
  347. identityInfoDf.loc[identityInfoIndex, '学历'] = row1[3]
  348. identityInfoDf.loc[identityInfoIndex, '学位'] = row1[4]
  349. identityInfoDf.loc[identityInfoIndex, '通讯地址'] = row1[8].replace("\n", "")
  350. identityInfoDf.loc[identityInfoIndex, '就业状况'] = row1[5]
  351. mobileDf = dfObj["mobileDf"];
  352. identityInfoDf.loc[identityInfoIndex, '历史手机号码数'] = mobileDf.index.size
  353. reportTime = queryInfo["reportTime"]
  354. identityInfoDf.loc[identityInfoIndex, '近3个月手机号码数'] = getLastMonthMobileCount(mobileDf,3,reportTime)
  355. identityInfoDf.loc[identityInfoIndex, '近6个月手机号码数'] = getLastMonthMobileCount(mobileDf, 6,reportTime)
  356. identityInfoDf.loc[identityInfoIndex, '近12个月手机号码数'] = getLastMonthMobileCount(mobileDf, 12,reportTime)
  357. identityInfoDf.loc[identityInfoIndex, '近24个月手机号码数'] = getLastMonthMobileCount(mobileDf, 24,reportTime)
  358. #最近几个月电话号码数
  359. def getLastMonthMobileCount(df, month,reportTime):
  360. # 当前日期
  361. last1MonthDateStr = reportTime
  362. # 最近一个月
  363. lastMonthDate = np.datetime64(last1MonthDateStr, "D") - np.timedelta64(30 * month, 'D')
  364. lastMonthMobileDf = df[df[5] >= str(lastMonthDate)]
  365. return lastMonthMobileDf.shape[0];
  366. # 配偶姓名
  367. # 配偶证件号码
  368. # 配偶工作单位
  369. # 配偶联系电话
  370. def parseMate(dfObj):
  371. df = dfObj["df"];
  372. if not df.empty:
  373. row1 = df.loc[1, :]
  374. mate["mateName"] = row1[0] # 配偶姓名
  375. mate["mateCardId"] = row1[2] # 配偶证件号码
  376. mate["mateWorkCompany"] = row1[3].replace("\n", ""); # 配偶工作单位
  377. mate["mateContactTel"] = row1[4]; # 配偶联系电话
  378. mateInfoDf.loc[mateInfoIndex, '姓名'] = row1[0]
  379. mateInfoDf.loc[mateInfoIndex, '证件号码'] = row1[2]
  380. mateInfoDf.loc[mateInfoIndex, '工作单位'] = row1[3].replace("\n", "");
  381. mateInfoDf.loc[mateInfoIndex, '联系电话'] = row1[4].replace("\n", "");
  382. #解析居住信息
  383. def parseLiveInfo(dfObj):
  384. df = dfObj["df"];
  385. if not df.empty:
  386. row1 = df.loc[1, :]
  387. liveInfoDf.loc[liveInfoIndex, '居住地址'] = row1[1]
  388. liveInfoDf.loc[liveInfoIndex, '住宅电话'] = row1[2]
  389. liveInfoDf.loc[liveInfoIndex, '历史居住地址个数'] = df.index.size-1;
  390. curDate = np.datetime64(time.strftime("%Y-%m-%d"));
  391. last3year = str(curDate)[0:4]
  392. last3yearDate = str(int(last3year)-3)+str(curDate)[4:10]
  393. lastLiveDf = df[df[4]>=last3yearDate];
  394. liveInfoDf.loc[liveInfoIndex, '最近3年内居住地址个数'] = lastLiveDf.index.size-1;
  395. houseIndex = df[df[3]=='自置'].index.size>0
  396. if (houseIndex):
  397. houseStr = '是'
  398. else:
  399. houseStr= '否'
  400. liveInfoDf.loc[liveInfoIndex, '当前居住状况-是否具有自有住房'] = houseStr;
  401. liveInfoDf.loc[liveInfoIndex, '居住状况'] = row1[3]
  402. liveInfoDf.loc[liveInfoIndex, '信息更新日期'] = row1[4]
  403. #解析职业信息
  404. def parseOccupationInfoDf(dfObj):
  405. df = dfObj["df"];
  406. if not df.empty:
  407. occIndex1 = 0#判断职业从哪行开始
  408. for i in range(0,df.index.size):
  409. if df.loc[i,:].dropna().tolist()==occupationInfo_header1:
  410. occIndex1=i;
  411. break;
  412. occDf = df[1:occIndex1].reset_index(drop=True)#工作单位
  413. occDfNew = pd.DataFrame()
  414. occDf1New = pd.DataFrame()
  415. #删除为none的列 合并的bug TODO
  416. for i in range(0,occDf.index.size):
  417. occDfNew = occDfNew.append([pd.DataFrame(occDf.iloc[i].dropna().reset_index(drop=True)).T],ignore_index=True)
  418. occDf1 = df[occIndex1+1:df.index.size].reset_index(drop=True) #职业
  419. for i in range(0,occDf1.index.size):
  420. occDf1New = occDf1New.append([pd.DataFrame(occDf1.iloc[i].dropna().reset_index(drop=True)).T], ignore_index=True)
  421. occDf = pd.concat([occDfNew, occDf1New], axis=1, ignore_index=True)#合并df
  422. row = occDf.loc[0, :].dropna()#取最新
  423. occupationInfoDf.loc[occupationInfoIndex, '工作单位'] = row[1]
  424. last3yearDate = utils.getLastMonthDate(queryInfo['reportTime'],12*3)
  425. occDf = utils.replaceDateColIdx(occDf,occDf.columns.size-1)
  426. dateIndex = occDf.columns.size-1;#日期列
  427. last3yearOccDf = occDf[occDf[dateIndex]>=last3yearDate]
  428. occupationInfoDf.loc[occupationInfoIndex, '最近3年内工作单位数'] = last3yearOccDf.index.size;
  429. occupationInfoDf.loc[occupationInfoIndex, '单位电话'] = row[4];
  430. reportTime = queryInfo['reportTime']
  431. try:
  432. minDateIndex = np.argmin(occDf[dateIndex]);
  433. maxDateIndex = np.argmax(occDf[dateIndex]);
  434. rowYearMin = occDf.loc[minDateIndex, :].dropna()
  435. rowYearMax = occDf.loc[maxDateIndex, :].dropna()
  436. if rowYearMin[10]!="--":
  437. occupationInfoDf.loc[occupationInfoIndex, '最早进入本单位年份距报告日期时长'] = int(str(np.datetime64(reportTime, "Y")))-int(rowYearMin[10])
  438. if rowYearMax[10]!="--":
  439. occupationInfoDf.loc[occupationInfoIndex, '最新进入本单位年份距报告日期时长'] = int(str(np.datetime64(reportTime, "Y")))-int(rowYearMax[10])
  440. except:
  441. logger.error("最早进入本单位年份距报告日期时长解析异常")
  442. row0 = occDf.loc[0,:].dropna().reset_index(drop=True)#最新
  443. occupationInfoDf.loc[occupationInfoIndex, '单位性质'] =row0[2]
  444. occupationInfoDf.loc[occupationInfoIndex, '单位地址'] = row0[3].replace("\n","")
  445. occupationInfoDf.loc[occupationInfoIndex, '职业'] = row0[6]
  446. occupationInfoDf.loc[occupationInfoIndex, '行业'] = row0[7]
  447. occupationInfoDf.loc[occupationInfoIndex, '职务'] = row0[8]
  448. occupationInfoDf.loc[occupationInfoIndex, '职称'] = row0[9]
  449. occupationInfoDf.loc[occupationInfoIndex, '进入本单位年份'] = row0[10]
  450. occupationInfoDf.loc[occupationInfoIndex, '信息更新日期'] = row0[11]
  451. occupationInfoDf.loc[occupationInfoIndex, '历史工作单位数'] = occDf1.index.size
  452. # 日期相减离当前时间月份
  453. # 贷款账龄(月数)=当前日期(2020-04-01)-最小月份的1日(2019.2->2019-12-01)=4
  454. # def difMonth(dateStr):
  455. # return int(int(str(np.datetime64(time.strftime("%Y-%m-%d")) -
  456. # np.datetime64(dateStr.replace('.', '-'), "D")).split(" ")[0]) / 30);
  457. # 信贷交易明细汇总
  458. def parseLoanTradeInfo(dfObj):
  459. df = dfObj["df"];
  460. # row1 = df.loc[1, :]
  461. if not df.empty:
  462. loanMonthDf = df[1: 4]
  463. loanMonthDf = loanMonthDf.reset_index(drop=True)
  464. briefInfoDf_loanTradeInfo.loc[loanTradeInfoIndex, '个人住房贷款账户数'] = utils.toInt(loanMonthDf.loc[0, :][2])
  465. briefInfoDf_loanTradeInfo.loc[loanTradeInfoIndex,'个人商用房贷款(包括商住两用)账户数']=utils.toInt(loanMonthDf.loc[1, :][2])
  466. briefInfoDf_loanTradeInfo.loc[loanTradeInfoIndex, '其他类贷款账户数'] = utils.toInt(loanMonthDf.loc[2, :][2])
  467. creditCardDf = df[4: 6];
  468. creditCardDf = creditCardDf.reset_index(drop=True)
  469. briefInfoDf_loanTradeInfo.loc[loanTradeInfoIndex, '贷记卡账户数'] = utils.toInt(creditCardDf.loc[0, :][2])
  470. briefInfoDf_loanTradeInfo.loc[loanTradeInfoIndex, '准贷记卡账户数'] = utils.toInt(creditCardDf.loc[1, :][2])
  471. # 解析呆账信息汇总
  472. def parseBadDebtsInfoSumDf(dfObj):
  473. df = dfObj["df"];
  474. if not df.empty:
  475. row1 = df.loc[2, :]
  476. briefInfoDf_badDebtsInfoSum.loc[badDebtsInfoIndex, '账户数'] = row1[0];
  477. briefInfoDf_badDebtsInfoSum.loc[badDebtsInfoIndex, '余额'] = utils.replaceAmt(row1[1]);
  478. # 解析被追偿信息汇总
  479. def parseRecoveryInfoSum(dfObj):
  480. df = dfObj["df"];
  481. if not df.empty:
  482. row1 = df.loc[2, :]
  483. row2 = df.loc[3, :]
  484. row3 = df.loc[4, :]
  485. overdueBrief["disposalInfoSumAccount"] = row1[1]; # 资产处置信息汇总笔数
  486. briefInfoDf_recoveryInfoSum.loc[recoveryInfoSumIndex, '资产处置业务账户数'] = row1[1];
  487. overdueBrief["disposalInfoSumAmt"] = row1[2]; # 资产处置信息汇总余额
  488. briefInfoDf_recoveryInfoSum.loc[recoveryInfoSumIndex, '资产处置业务余额'] = utils.replaceAmt(row1[2]);
  489. overdueBrief["advanceInfoSumAccount"] = row2[1]; # 垫款业务笔数
  490. briefInfoDf_recoveryInfoSum.loc[recoveryInfoSumIndex, '垫款业务账户数'] = row2[1];
  491. overdueBrief["advanceInfoSumAmt"] = row2[2]; # 垫款业务余额
  492. briefInfoDf_recoveryInfoSum.loc[recoveryInfoSumIndex, '垫款业务余额'] = utils.replaceAmt(row2[2]);
  493. briefInfoDf_recoveryInfoSum.loc[recoveryInfoSumIndex, '合计总账户数'] = row3[1];
  494. briefInfoDf_recoveryInfoSum.loc[recoveryInfoSumIndex, '合计总余额'] = utils.replaceAmt(row3[2]);
  495. # 贷款逾期账户数
  496. # 贷款逾期月份数
  497. # 贷款单月最高逾期总额
  498. # 贷款最长逾期月数
  499. def parseOverdueInfoSum(dfObj):
  500. df = dfObj["df"];
  501. if not df.empty:
  502. row2= df.loc[2, :]
  503. row3 = df.loc[3, :]
  504. row4 = df.loc[4, :]
  505. row5 = df.loc[5, :]
  506. row6 = df.loc[6, :]
  507. #这块的数据需要进行出来 TODO
  508. briefInfoDf_overdueInfoSum.loc[overdueInfoSumIndex, '非循环贷帐户账户数'] = utils.toInt(row2[1]);
  509. briefInfoDf_overdueInfoSum.loc[overdueInfoSumIndex, '非循环贷帐户月份数'] = utils.toInt(row2[2]);
  510. briefInfoDf_overdueInfoSum.loc[overdueInfoSumIndex, '非循环贷帐户单月最高逾期总额'] = utils.replaceAmt(row2[3]);
  511. briefInfoDf_overdueInfoSum.loc[overdueInfoSumIndex, '非循环贷帐户最长逾期月数'] = utils.toInt(row2[4]);
  512. briefInfoDf_overdueInfoSum.loc[overdueInfoSumIndex, '循环额度下分账户账户数'] = utils.toInt(row3[1]);
  513. briefInfoDf_overdueInfoSum.loc[overdueInfoSumIndex, '循环额度下分账户月份数'] = utils.toInt(row3[2]);
  514. briefInfoDf_overdueInfoSum.loc[overdueInfoSumIndex, '循环额度下分账户单月最高逾期总额'] = utils.replaceAmt(row3[3]);
  515. briefInfoDf_overdueInfoSum.loc[overdueInfoSumIndex, '循环额度下分账户最长逾期月数'] = utils.toInt(row3[4]);
  516. briefInfoDf_overdueInfoSum.loc[overdueInfoSumIndex, '循环贷账户账户数'] = utils.toInt(row4[1]);
  517. briefInfoDf_overdueInfoSum.loc[overdueInfoSumIndex, '循环贷账户月份数'] = utils.toInt(row4[2]);
  518. briefInfoDf_overdueInfoSum.loc[overdueInfoSumIndex, '循环贷账户单月最高逾期总额'] = utils.replaceAmt(row4[3]);
  519. briefInfoDf_overdueInfoSum.loc[overdueInfoSumIndex, '循环贷账户最长逾期月数'] = utils.toInt(row4[4]);
  520. briefInfoDf_overdueInfoSum.loc[overdueInfoSumIndex, '贷记卡账户账户数'] = utils.toInt(row5[1]);
  521. briefInfoDf_overdueInfoSum.loc[overdueInfoSumIndex, '贷记卡账户月份数'] = utils.toInt(row5[2]);
  522. briefInfoDf_overdueInfoSum.loc[overdueInfoSumIndex, '贷记卡账户单月逾期总额'] = utils.replaceAmt(row5[3]);
  523. briefInfoDf_overdueInfoSum.loc[overdueInfoSumIndex, '贷记卡账户最长逾期月数'] = utils.toInt(row5[4]);
  524. briefInfoDf_overdueInfoSum.loc[overdueInfoSumIndex, '准贷记卡账户账户数'] = utils.toInt(row6[1]);
  525. briefInfoDf_overdueInfoSum.loc[overdueInfoSumIndex, '准贷记卡账户月份数'] = utils.toInt(row6[2]);
  526. briefInfoDf_overdueInfoSum.loc[overdueInfoSumIndex, '准贷记卡账户单月透支总额'] = utils.replaceAmt(row6[3]);
  527. briefInfoDf_overdueInfoSum.loc[overdueInfoSumIndex, '准贷记卡账户最长透支月数'] = utils.toInt(row6[4]);
  528. overdueInfoAccountDf = df[df[1] != '--'];
  529. overdueInfoAccountDf = overdueInfoAccountDf[2:7]
  530. briefInfoDf_overdueInfoSum.loc[overdueInfoSumIndex, '该用户所有逾期账户最长逾期/透支月数最大值']=np.max(overdueInfoAccountDf[4].astype('int'))
  531. #np.sum(overdueInfoAccountDf[1])
  532. briefInfoDf_overdueInfoSum.loc[overdueInfoSumIndex, '该用户所有逾期账户数加总']= np.sum(overdueInfoAccountDf[1].astype('int'))# TODO
  533. # briefInfoDf_overdueInfoSum.loc[overdueInfoSumIndex, '该用户过去5年出现逾期的所有账户数目']=None# TODO
  534. # 未结清贷款法人机构数 从“未结清贷款信息汇总”中直接提取LoanLegalOrgNum
  535. # 未结清贷款机构数 从“未结清贷款信息汇总”中直接提取LoanOrgNum
  536. # 未结清贷款笔数 从“未结清贷款信息汇总”中直接提取CountNum
  537. # 未结清贷款合同总额 从“未结清贷款信息汇总”中直接提取ContractProfits
  538. # 未结清贷款合同余额 从“未结清贷款信息汇总”中直接提取Balance
  539. # 未结清贷款近6月平均应还款 从“未结清贷款信息汇总”中直接提取Last6MothsAvgRepayAmount
  540. # 个人贷款未结清笔数 "从“未结清贷款信息汇总”计算客户符合以下条件的贷款笔数
  541. # 1.贷款类型不为('%个人助学贷款%' ,'%农户贷款%')
  542. # 2.贷款额度>100元
  543. # 3.贷款状态不为“结清”"
  544. # 非循环贷账户信息汇总
  545. def doFilterCalc(dfx):
  546. dfx = dfx.replace('--', 0)
  547. return dfx;
  548. # 科学计数法转换
  549. def replaceAmt(dfx):
  550. return dfx.str.replace(',', '')
  551. # 非循环贷账户信息汇总
  552. def parseLoanAccountInfoSum(dfObj):
  553. df = dfObj["df"];
  554. if not df.empty:
  555. loanAccountInfoSumDf = df[2:3];
  556. loanAccountInfoSumDf = doFilterCalc(loanAccountInfoSumDf); # 替换--为0
  557. loanAccountInfoSumDf = loanAccountInfoSumDf.reset_index(drop=True)
  558. row0 = loanAccountInfoSumDf.loc[0,:]
  559. briefInfoDf_loanTradeCreditInfo.loc[loanTradeCreditInfoIndex, '非循环贷账户管理机构数'] = int(row0[0])
  560. briefInfoDf_loanTradeCreditInfo.loc[loanTradeCreditInfoIndex, '非循环贷账户账户数'] = int(row0[1])
  561. briefInfoDf_loanTradeCreditInfo.loc[loanTradeCreditInfoIndex, '非循环贷账户授信总额'] = int(utils.replaceAmt(row0[2]))
  562. briefInfoDf_loanTradeCreditInfo.loc[loanTradeCreditInfoIndex, '非循环贷账户余额'] = int(utils.replaceAmt(row0[3]))
  563. briefInfoDf_loanTradeCreditInfo.loc[loanTradeCreditInfoIndex, '非循环贷账户6月平均应还款'] = int(utils.replaceAmt(row0[4]))
  564. # 循环额度下分账户
  565. def parseCycleCreditAccountInfoSum(dfObj):
  566. df = dfObj["df"];
  567. if not df.empty:
  568. cycleCreditAccountInfoSumDf = df[2:3];
  569. cycleCreditAccountInfoSumDf = doFilterCalc(cycleCreditAccountInfoSumDf); # 替换--为0
  570. cycleCreditAccountInfoSumDf = cycleCreditAccountInfoSumDf.reset_index(drop=True)
  571. row0 = cycleCreditAccountInfoSumDf.loc[0,:]
  572. briefInfoDf_loanTradeCreditInfo.loc[loanTradeCreditInfoIndex, '循环额度下分账户管理机构数'] = int(row0[0])
  573. briefInfoDf_loanTradeCreditInfo.loc[loanTradeCreditInfoIndex, '循环额度下分账户账户数'] = int(row0[1])
  574. briefInfoDf_loanTradeCreditInfo.loc[loanTradeCreditInfoIndex, '循环额度下分账户授信总额'] = int(utils.replaceAmt(row0[2]))
  575. briefInfoDf_loanTradeCreditInfo.loc[loanTradeCreditInfoIndex, '循环额度下分账户余额'] = int(utils.replaceAmt(row0[3]))
  576. briefInfoDf_loanTradeCreditInfo.loc[loanTradeCreditInfoIndex, '循环额度下分账户6月平均应还款'] = int(utils.replaceAmt(row0[4]))
  577. # 循环贷账户信息
  578. def parseCyleLoanAccountInfoSum(dfObj):
  579. df = dfObj["df"];
  580. if not df.empty:
  581. cycleLoanAccountInfoSumDf = df[2:3];
  582. cycleLoanAccountInfoSumDf = doFilterCalc(cycleLoanAccountInfoSumDf); # 替换--为0
  583. cycleLoanAccountInfoSumDf = cycleLoanAccountInfoSumDf.reset_index(drop=True)
  584. row0 = cycleLoanAccountInfoSumDf.loc[0,:]
  585. briefInfoDf_loanTradeCreditInfo.loc[loanTradeCreditInfoIndex, '循环贷账户管理机构数'] = int(row0[0])
  586. briefInfoDf_loanTradeCreditInfo.loc[loanTradeCreditInfoIndex, '循环贷账户账户数'] = int(row0[1])
  587. briefInfoDf_loanTradeCreditInfo.loc[loanTradeCreditInfoIndex, '循环贷账户授信总额'] = int(utils.replaceAmt(row0[2]))
  588. briefInfoDf_loanTradeCreditInfo.loc[loanTradeCreditInfoIndex, '循环贷账户余额'] = int(utils.replaceAmt(row0[3]))
  589. briefInfoDf_loanTradeCreditInfo.loc[loanTradeCreditInfoIndex, '循环贷账户6月平均应还款'] = int(utils.replaceAmt(row0[4]))
  590. # 解析贷记卡信息汇总,包含准贷记卡
  591. def parseCreditCardInfoSum(dfObj):
  592. df = dfObj["df"];
  593. if not df.empty:
  594. creditCardInfoSumDf = df[2:3];
  595. creditCardInfoSumDf = doFilterCalc(creditCardInfoSumDf); # 替换--为0
  596. creditCardInfoSumDf = creditCardInfoSumDf.reset_index(drop=True)
  597. row0 = creditCardInfoSumDf.loc[0, :]
  598. briefInfoDf_loanTradeCreditInfo.loc[loanTradeCreditInfoIndex, '贷记卡发卡机构数'] = int(row0[0])
  599. briefInfoDf_loanTradeCreditInfo.loc[loanTradeCreditInfoIndex, '贷记卡账户数'] = int(row0[1])
  600. briefInfoDf_loanTradeCreditInfo.loc[loanTradeCreditInfoIndex, '贷记卡授信总额'] = int(utils.replaceAmt(row0[2]))
  601. briefInfoDf_loanTradeCreditInfo.loc[loanTradeCreditInfoIndex, '贷记卡单家机构最高授信额'] = int(utils.replaceAmt(row0[3]))
  602. briefInfoDf_loanTradeCreditInfo.loc[loanTradeCreditInfoIndex, '贷记卡单家机构最低授信额'] = int(utils.replaceAmt(row0[4]))
  603. briefInfoDf_loanTradeCreditInfo.loc[loanTradeCreditInfoIndex, '贷记卡已用额度'] = int(utils.replaceAmt(row0[5]))
  604. briefInfoDf_loanTradeCreditInfo.loc[loanTradeCreditInfoIndex, '贷记卡最近6个月平均使用额度'] = int(utils.replaceAmt(row0[6]))
  605. # 解析贷记卡信息汇总,包含准贷记卡
  606. def parseCreditCardInfoSumZ(dfObj):
  607. df = dfObj["df"];
  608. if not df.empty:
  609. creditCardInfoSumDfZ = df[2:3];
  610. creditCardInfoSumDfZ = doFilterCalc(creditCardInfoSumDfZ);
  611. creditCardInfoSumDfZ = creditCardInfoSumDfZ.reset_index(drop=True)
  612. row0 = creditCardInfoSumDfZ.loc[0, :]
  613. briefInfoDf_loanTradeCreditInfo.loc[loanTradeCreditInfoIndex, '准贷记卡发卡机构数'] = int(row0[0])
  614. briefInfoDf_loanTradeCreditInfo.loc[loanTradeCreditInfoIndex, '准贷记卡账户数'] = int(row0[1])
  615. briefInfoDf_loanTradeCreditInfo.loc[loanTradeCreditInfoIndex, '准贷记卡授信总额'] = int(utils.replaceAmt(row0[2]))
  616. briefInfoDf_loanTradeCreditInfo.loc[loanTradeCreditInfoIndex, '准贷记卡单家机构最高授信额'] = int(utils.replaceAmt(row0[3]))
  617. briefInfoDf_loanTradeCreditInfo.loc[loanTradeCreditInfoIndex, '准贷记卡单家机构最低授信额'] = int(utils.replaceAmt(row0[4]))
  618. briefInfoDf_loanTradeCreditInfo.loc[loanTradeCreditInfoIndex, '准贷记卡已用额度'] = int(utils.replaceAmt(row0[5]))
  619. briefInfoDf_loanTradeCreditInfo.loc[loanTradeCreditInfoIndex, '准贷记卡最近6个月平均使用额度'] = int(utils.replaceAmt(row0[6]))
  620. #相关还款责任
  621. def parseRepaymentSum(dfObj):
  622. df = dfObj["df"];
  623. if not df.empty:
  624. row4 = df.loc[4,:].dropna().reset_index(drop=True)#第4行 为个人
  625. row8 = None
  626. if df.index.size ==9:
  627. row8 = df.loc[8,:].dropna().reset_index(drop=True)#第8行 为企业
  628. perAccountNum = 0;#个人账户数
  629. orgAccountNum = 0; # 企业账户数
  630. totalAccountNum = 0;#总账户数
  631. guaranteeAccountNum = 0;#相关还款责任总账户数-担保责任
  632. otherAccountNum =0;#相关还款责任总账户数-其他
  633. perGuaranteeAmt = 0#个人担保金额及其他
  634. orgGuaranteeAmt = 0#企业担保金额及其他
  635. totalGuaranteeAmt = 0;#总担保金额
  636. guaranteeAmt = 0;#相关还款责任总担保金额
  637. otherPaymentAmt = 0;#其他还款责任金额
  638. perGuaranteeBalance = 0 # 个人担保余额及其他
  639. orgGuaranteeBalance = 0 # 企业担保余额及其他
  640. totalGuaranteeBalance = 0;#总担保余额
  641. guaranteeBalance = 0;#相关还款责任总担保余额
  642. otherPaymentBalance = 0; # 其他还款责任余额
  643. #计算总账户数
  644. if row4[0] !="--":
  645. perAccountNum=perAccountNum+utils.toInt(row4[0])
  646. guaranteeAccountNum = guaranteeAccountNum + utils.toInt(row4[0])#个人担保责任账户数
  647. if row4[3] !="--":
  648. perAccountNum = perAccountNum + utils.toInt(row4[3])#其他
  649. otherAccountNum = otherAccountNum + utils.toInt(row4[3]) # 其他
  650. if row8 != None:
  651. if row8[0] != "--":
  652. orgAccountNum = orgAccountNum + utils.toInt(row8[0])
  653. guaranteeAccountNum = guaranteeAccountNum + utils.toInt(row8[0])#企业担保责任账户数
  654. if row8[3] != "--":
  655. orgAccountNum = orgAccountNum + utils.toInt(row8[3])#其他
  656. otherAccountNum = otherAccountNum + utils.toInt(row8[3]) # 其他
  657. totalAccountNum = perAccountNum+orgAccountNum
  658. #计算担保金额
  659. if row4[1] !="--":
  660. perGuaranteeAmt=perGuaranteeAmt+utils.replaceAmt(row4[1])#担保
  661. guaranteeAmt = guaranteeAmt + utils.replaceAmt(row4[1]) # 担保
  662. if row4[4] !="--":
  663. perGuaranteeAmt = perGuaranteeAmt + utils.replaceAmt(row4[4])#其他
  664. otherPaymentAmt = otherPaymentAmt + utils.replaceAmt(row4[4]) # 其他
  665. if row8 != None:
  666. if row8[1] != "--":
  667. orgGuaranteeAmt = orgGuaranteeAmt + utils.replaceAmt(row8[1])#担保
  668. guaranteeAmt = guaranteeAmt + utils.replaceAmt(row8[1]) # 担保
  669. if row8[4] != "--":
  670. orgGuaranteeAmt = orgGuaranteeAmt + utils.replaceAmt(row8[4])#其他
  671. otherPaymentAmt = otherPaymentAmt + utils.replaceAmt(row8[4]) # 其他
  672. totalGuaranteeAmt = perGuaranteeAmt + orgGuaranteeAmt
  673. # 计算余额
  674. if row4[2] !="--":
  675. perGuaranteeBalance=perGuaranteeBalance+utils.replaceAmt(row4[2])
  676. guaranteeBalance=guaranteeBalance+utils.replaceAmt(row4[2])#个人担保余额
  677. if row4[5] !="--":
  678. perGuaranteeBalance = perGuaranteeBalance + utils.replaceAmt(row4[5])#其他
  679. otherPaymentBalance = otherPaymentBalance + utils.replaceAmt(row4[5]) # 其他
  680. if row8 != None:
  681. if row8[2] != "--":
  682. orgGuaranteeBalance = orgGuaranteeBalance + utils.replaceAmt(row8[2])
  683. guaranteeBalance = guaranteeBalance + utils.replaceAmt(row8[2])#企业担保余额
  684. if row8[5] != "--":
  685. orgGuaranteeBalance = orgGuaranteeBalance + utils.replaceAmt(row8[5])
  686. otherPaymentBalance = otherPaymentBalance + utils.replaceAmt(row8[5]) # 其他
  687. totalGuaranteeBalance = perGuaranteeBalance + orgGuaranteeBalance
  688. briefInfoDf_loanTradeCreditInfo.loc[loanTradeCreditInfoIndex, '相关还款责任总账户数(担保+其他+个人+企业)'] =totalAccountNum
  689. briefInfoDf_loanTradeCreditInfo.loc[loanTradeCreditInfoIndex, '相关还款责任总担保金额+总还款责任金额(个人+企业)'] =totalGuaranteeAmt
  690. briefInfoDf_loanTradeCreditInfo.loc[loanTradeCreditInfoIndex, '相关还款责任账户总担保余额+总其他余额(个人+企业)'] =totalGuaranteeBalance
  691. if totalGuaranteeAmt !=0:
  692. briefInfoDf_loanTradeCreditInfo.loc[loanTradeCreditInfoIndex, '相关还款责任账户总担保余额+总其他余额(个人+企业)/相关还款责任账户总担保金额+总其他金额(个人+企业)'] =\
  693. round(totalGuaranteeBalance / totalGuaranteeAmt, 2)
  694. briefInfoDf_loanTradeCreditInfo.loc[loanTradeCreditInfoIndex, '相关还款责任担保总账户数-个人'] =perAccountNum
  695. briefInfoDf_loanTradeCreditInfo.loc[loanTradeCreditInfoIndex, '相关还款责任总担保金额-个人'] =perGuaranteeAmt
  696. briefInfoDf_loanTradeCreditInfo.loc[loanTradeCreditInfoIndex, '相关还款责任总担保余额-个人'] =perGuaranteeBalance
  697. if perGuaranteeBalance !=0:
  698. briefInfoDf_loanTradeCreditInfo.loc[loanTradeCreditInfoIndex, '相关还款责任总担保余额-个人/相关还款责任总担保金额-个人'] = round(perGuaranteeBalance/perGuaranteeBalance,2)
  699. briefInfoDf_loanTradeCreditInfo.loc[loanTradeCreditInfoIndex, '相关还款责任总账户数-企业'] =orgAccountNum
  700. briefInfoDf_loanTradeCreditInfo.loc[loanTradeCreditInfoIndex, '相关还款责任总担保金额-企业'] =orgGuaranteeAmt
  701. briefInfoDf_loanTradeCreditInfo.loc[loanTradeCreditInfoIndex, '相关还款责任总担保余额-企业'] =orgGuaranteeBalance
  702. if orgGuaranteeAmt!=0:
  703. briefInfoDf_loanTradeCreditInfo.loc[loanTradeCreditInfoIndex, '相关还款责任总担保余额-企业/相关还款责任总担保金额-企业'] = round(orgGuaranteeBalance/orgGuaranteeAmt,2)
  704. briefInfoDf_loanTradeCreditInfo.loc[loanTradeCreditInfoIndex, '相关还款责任总账户数-担保责任'] =guaranteeAccountNum
  705. briefInfoDf_loanTradeCreditInfo.loc[loanTradeCreditInfoIndex, '相关还款责任总担保金额-担保责任'] =guaranteeAmt
  706. briefInfoDf_loanTradeCreditInfo.loc[loanTradeCreditInfoIndex, '相关还款责任账户总担保余额-担保责任'] =guaranteeBalance
  707. if guaranteeAmt!=0:
  708. briefInfoDf_loanTradeCreditInfo.loc[loanTradeCreditInfoIndex, '相关还款责任总担保余额-担保责任/相关还款责任总担保金额-担保责任'] =round(guaranteeBalance/guaranteeAmt,2)
  709. briefInfoDf_loanTradeCreditInfo.loc[loanTradeCreditInfoIndex, '相关还款责任总账户数-其他'] =otherAccountNum
  710. briefInfoDf_loanTradeCreditInfo.loc[loanTradeCreditInfoIndex, '相关还款责任总担保金额-其他'] =otherPaymentAmt
  711. briefInfoDf_loanTradeCreditInfo.loc[loanTradeCreditInfoIndex, '相关还款责任总担保余额-其他'] =otherPaymentBalance
  712. if otherPaymentAmt!=0:
  713. briefInfoDf_loanTradeCreditInfo.loc[loanTradeCreditInfoIndex, '相关还款责任账户总担保余额-其他/相关还款责任账户总担保金额-其他'] =round(otherPaymentBalance/otherPaymentAmt,2)
  714. #解析公共信息汇总
  715. def parsePublicInfoBrief(dfObj):
  716. df = dfObj["df"];
  717. if not df.empty:
  718. publicInfoBrief = df[1:6];
  719. publicInfoBrief = publicInfoBrief.reset_index(drop=True)
  720. row0 = publicInfoBrief.loc[0, :]
  721. row1 = publicInfoBrief.loc[1, :]
  722. row2 = publicInfoBrief.loc[2, :]
  723. row3 = publicInfoBrief.loc[3, :]
  724. publicInfoBriefDf.loc[publicInfoBriefIndex, '欠税信息-记录数'] = int(row0[1])
  725. publicInfoBriefDf.loc[publicInfoBriefIndex, '欠税信息-涉及金额'] = int(utils.replaceAmt(row0[2]))
  726. publicInfoBriefDf.loc[publicInfoBriefIndex, '民事判决信息-记录数'] = int(row1[1])
  727. publicInfoBriefDf.loc[publicInfoBriefIndex, '民事判决信息-涉及金额'] = int(utils.replaceAmt(row1[2]))
  728. publicInfoBriefDf.loc[publicInfoBriefIndex, '强制执行信息-记录数'] = int(row2[1])
  729. publicInfoBriefDf.loc[publicInfoBriefIndex, '强制执行信息-涉及金额'] = int(utils.replaceAmt(row2[2]))
  730. publicInfoBriefDf.loc[publicInfoBriefIndex, '行政处罚信息-记录数'] = int(row3[1])
  731. publicInfoBriefDf.loc[publicInfoBriefIndex, '行政处罚信息-涉及金额'] = int(utils.replaceAmt(row3[2]))
  732. #解析查询信息汇总
  733. def parseQueryRecordSum(dfObj):
  734. df = dfObj["df"];
  735. if not df.empty:
  736. queryRecordSumDfTmp = df[2:3];
  737. queryRecordSumDfTmp = queryRecordSumDfTmp.reset_index(drop=True)
  738. row0 = queryRecordSumDfTmp.loc[0, :]
  739. queryRecordSumDf.loc[queryRecordSumIndex, '近1月内的查询机构数-贷款审批'] =int(row0[0])
  740. queryRecordSumDf.loc[queryRecordSumIndex, '近1月内的查询机构数-信用卡审批'] =int(row0[1])
  741. queryRecordSumDf.loc[queryRecordSumIndex, '近1月内的查询次数-贷款审批'] =int(row0[2])
  742. queryRecordSumDf.loc[queryRecordSumIndex, '近1月内的查询次数-信用卡审批'] =int(row0[3])
  743. queryRecordSumDf.loc[queryRecordSumIndex, '近1月内的查询次数-本人查询'] =int(row0[4])
  744. queryRecordSumDf.loc[queryRecordSumIndex, '近2年内的查询次数-贷后管理'] =int(row0[5])
  745. queryRecordSumDf.loc[queryRecordSumIndex, '近2年内的查询次数-担保资格审查'] =int(row0[6])
  746. # 解析查询记录明细
  747. def parseQueryInfoDetail(dfObj):
  748. df = dfObj["df"];
  749. reportTime = queryInfo["reportTime"];
  750. if not df.empty:
  751. df = utils.replaceDateCol(df)
  752. df = df[1:df.index.size] # 去掉表头
  753. queryRecordDetailDf.loc[queryRecordDetailIndex, '近1月查询次数'] =qip.getLastMonthQueryTimes(df, 1, "",reportTime)
  754. queryRecordDetailDf.loc[queryRecordDetailIndex, '近3月查询次数'] =qip.getLastMonthQueryTimes(df, 3, "",reportTime)
  755. queryRecordDetailDf.loc[queryRecordDetailIndex, '近6月查询次数'] =qip.getLastMonthQueryTimes(df, 6, "",reportTime)
  756. queryRecordDetailDf.loc[queryRecordDetailIndex, '近12月查询次数'] =qip.getLastMonthQueryTimes(df, 12, "",reportTime)
  757. queryRecordDetailDf.loc[queryRecordDetailIndex, '最近1个月查询机构数'] =qip.getLastMonthQueryOrgTimes(df, 1, "", reportTime)
  758. queryRecordDetailDf.loc[queryRecordDetailIndex, '最近3个月查询机构数'] =qip.getLastMonthQueryOrgTimes(df, 3, "", reportTime)
  759. queryRecordDetailDf.loc[queryRecordDetailIndex, '最近6个月查询机构数'] =qip.getLastMonthQueryOrgTimes(df, 6, "", reportTime)
  760. queryRecordDetailDf.loc[queryRecordDetailIndex, '最近12个月查询机构数'] =qip.getLastMonthQueryOrgTimes(df, 12, "", reportTime)
  761. queryRecordDetailDf.loc[queryRecordDetailIndex, '最近24个月查询机构数'] =qip.getLastMonthQueryOrgTimes(df, 24, "", reportTime)
  762. queryRecordDetailDf.loc[queryRecordDetailIndex, '近3月查询次数贷款审批'] =qip.getLastMonthQueryTimes(df, 3, consts.loanApprove, reportTime)
  763. queryRecordDetailDf.loc[queryRecordDetailIndex, '近3月查询次数信用卡审批'] =qip.getLastMonthQueryTimes(df, 3, consts.creditCard, reportTime)
  764. queryRecordDetailDf.loc[queryRecordDetailIndex, '近6月查询次数贷款审批'] =qip.getLastMonthQueryTimes(df, 6, consts.loanApprove, reportTime)
  765. queryRecordDetailDf.loc[queryRecordDetailIndex, '近6月查询次数信用卡审批'] = qip.getLastMonthQueryTimes(df, 6, consts.creditCard, reportTime)
  766. queryRecordDetailDf.loc[queryRecordDetailIndex, '近12月查询次数贷款审批'] = qip.getLastMonthQueryTimes(df, 12, consts.loanApprove, reportTime)
  767. queryRecordDetailDf.loc[queryRecordDetailIndex, '近12月查询次数信用卡审批'] =qip.getLastMonthQueryTimes(df, 12, consts.creditCard, reportTime)
  768. queryRecordDetailDf.loc[queryRecordDetailIndex, '近3月查询机构数贷款审批'] =qip.getLastMonthQueryOrgTimes(df, 3, consts.loanApprove, reportTime)
  769. queryRecordDetailDf.loc[queryRecordDetailIndex, '近3月查询机构数信用卡审批'] =qip.getLastMonthQueryOrgTimes(df, 3, consts.creditCard, reportTime)
  770. queryRecordDetailDf.loc[queryRecordDetailIndex, '近6月查询机构数贷款审批'] =qip.getLastMonthQueryOrgTimes(df, 6, consts.loanApprove, reportTime)
  771. queryRecordDetailDf.loc[queryRecordDetailIndex, '近6月查询机构数信用卡审批'] = qip.getLastMonthQueryOrgTimes(df, 6, consts.creditCard,reportTime)
  772. queryRecordDetailDf.loc[queryRecordDetailIndex, '近12月查询机构数贷款审批'] = qip.getLastMonthQueryOrgTimes(df, 12, consts.loanApprove, reportTime)
  773. queryRecordDetailDf.loc[queryRecordDetailIndex, '近12月查询机构数信用卡审批'] = qip.getLastMonthQueryOrgTimes(df, 12, consts.creditCard,reportTime)
  774. queryRecordDetailDf.loc[queryRecordDetailIndex, '最近6个月担保资格审查查询次数'] = qip.getLastMonthQueryOrgTimes(df, 6, consts.insuranceAprove,reportTime)
  775. queryRecordDetailDf.loc[queryRecordDetailIndex, '近12个月担保资格审查查询次数'] = qip.getLastMonthQueryOrgTimes(df, 12, consts.insuranceAprove,reportTime)
  776. queryRecordDetailDf.loc[queryRecordDetailIndex, '最近6个月贷后管理查询次数'] = qip.getLastMonthQueryOrgTimes(df, 6, consts.loanAfterMgr,reportTime)
  777. queryRecordDetailDf.loc[queryRecordDetailIndex, '最近12个月贷后管理查询次数'] = qip.getLastMonthQueryOrgTimes(df, 12, consts.loanAfterMgr,reportTime)
  778. queryRecordDetailDf.loc[queryRecordDetailIndex, '最后一次查询距离现在的月数贷款审批'] = qip.getLastTimeQueryMonth(df, consts.loanApprove,reportTime)
  779. queryRecordDetailDf.loc[queryRecordDetailIndex, '最近24个月贷后管理查询次数'] = qip.getLastMonthQueryTimes(df, 24, consts.loanAfterMgr, reportTime)
  780. queryRecordDetailDf.loc[queryRecordDetailIndex, '最近24个月贷款审批审批次数'] = qip.getLastMonthQueryTimes(df, 24, consts.loanApprove, reportTime)
  781. queryRecordDetailDf.loc[queryRecordDetailIndex, '最近24个月信用卡审批查询次数'] = qip.getLastMonthQueryTimes(df, 24, consts.creditCard,reportTime)
  782. queryRecordDetailDf.loc[queryRecordDetailIndex, '最近24个月担保资格审查查询次数'] = qip.getLastMonthQueryTimes(df, 24, consts.insuranceAprove,reportTime)
  783. #解析住房公积金
  784. def parseHousingFundRcd(df):
  785. if not df.empty:
  786. lastHousingFundRcdDf = df.sort_values(by=["信息更新日期"] , ascending=(False)).reset_index(drop=True)
  787. lastHousingFundRcdDf = lastHousingFundRcdDf[0:1]#最新
  788. row1 = lastHousingFundRcdDf.loc[0,:].dropna().reset_index(drop=True)
  789. housingFundRcdDf.loc[housingFundRcdIndex, '参缴地'] =row1[1]
  790. housingFundRcdDf.loc[housingFundRcdIndex, '参缴日期'] =row1[2]
  791. housingFundRcdDf.loc[housingFundRcdIndex, '初缴月份'] =row1[3]#初缴日期
  792. housingFundRcdDf.loc[housingFundRcdIndex, '缴至月份'] =row1[4]
  793. housingFundRcdDf.loc[housingFundRcdIndex, '缴费状态'] =row1[5]
  794. housingFundRcdDf.loc[housingFundRcdIndex, '月缴存额'] =row1[6]
  795. housingFundRcdDf.loc[housingFundRcdIndex, '个人存缴比例'] =row1[7]
  796. housingFundRcdDf.loc[housingFundRcdIndex, '单位存缴比例'] =row1[8]
  797. housingFundRcdDf.loc[housingFundRcdIndex, '缴费单位'] =row1[9]#扣缴单位
  798. housingFundRcdDf.loc[housingFundRcdIndex, '信息更新日期'] =row1[10]
  799. reportTime = queryInfo["reportTime"];
  800. lastDateStr = utils.getLastMonthDate(reportTime,12)
  801. avgHousingFundDf = df[df['缴至月份']>=lastDateStr]
  802. housingFundRcdDf.loc[housingFundRcdIndex, '最近1年公积金平均值'] = round(np.mean(avgHousingFundDf['月缴存额']),2)
  803. lastDateStr = utils.getLastMonthDate(reportTime, 12*3)
  804. avgHousingFundDf = df[df['缴至月份'] >= lastDateStr]
  805. housingFundRcdDf.loc[housingFundRcdIndex, '最近3年公积金平均值']= round(np.mean(avgHousingFundDf['月缴存额']),2)
  806. #解析贷款还款记录指标
  807. def parseLoanMergeAndPayRecordDf(df,payRcdDf):
  808. if not df.empty and not payRcdDf.empty:
  809. #正常
  810. normalDf = df[(df['账户状态'] != '结清') & (df['账户状态'] != '转出') & (df['账户状态'] != '呆账')]
  811. overduePayRcdDf = payRcdDf[payRcdDf['账户编号'].isin(normalDf['账户编号'].values)]
  812. overduePayRcdDf = utils.replacePayRcdStatus(overduePayRcdDf)
  813. #临时保存,不用过滤还款状态为0的
  814. payRcdMaxOverdueDf = overduePayRcdDf;
  815. overduePayRcdDf = overduePayRcdDf[overduePayRcdDf['还款状态']>0]
  816. loanAccountInfoDf.loc[loanAccountInfoIndex, '当前贷款逾期账户数'] = overduePayRcdDf['账户编号'].unique().size
  817. loanAccountInfoDf.loc[loanAccountInfoIndex, '当前贷款逾期账户数占比'] = round(loanAccountInfoDf.loc[loanAccountInfoIndex, '当前贷款逾期账户数']/df.index.size,2)
  818. #存在逾期的贷款账户 非结清的过滤出逾期的账户号
  819. overdueLoanDf = normalDf[normalDf['账户编号'].isin(overduePayRcdDf['账户编号'].values)]
  820. loanAccountInfoDf.loc[loanAccountInfoIndex, '当前贷款逾期机构数'] = overdueLoanDf['管理机构'].unique().size
  821. loanAccountInfoDf.loc[loanAccountInfoIndex, '当前贷款逾期机构数占比'] = round(loanAccountInfoDf.loc[loanAccountInfoIndex, '当前贷款逾期机构数'] / df['管理机构'].unique().size,2)
  822. #还款记录按日期排序最近3笔的最大逾期期数
  823. loanAccountInfoDf.loc[loanAccountInfoIndex, '近1月贷款的最大逾期期数'] = prp.getPayRcdMaxOverdueNum(payRcdMaxOverdueDf,1);
  824. loanAccountInfoDf.loc[loanAccountInfoIndex, '近3月贷款的最大逾期期数'] = prp.getPayRcdMaxOverdueNum(payRcdMaxOverdueDf, 3);
  825. loanAccountInfoDf.loc[loanAccountInfoIndex, '近6月贷款的最大逾期期数'] = prp.getPayRcdMaxOverdueNum(payRcdMaxOverdueDf, 6);
  826. loanAccountInfoDf.loc[loanAccountInfoIndex, '近9月贷款的最大逾期期数'] = prp.getPayRcdMaxOverdueNum(payRcdMaxOverdueDf, 9);
  827. loanAccountInfoDf.loc[loanAccountInfoIndex, '近24月贷款的最大逾期期数'] = prp.getPayRcdMaxOverdueNum(payRcdMaxOverdueDf, 24);
  828. reportTime = queryInfo["reportTime"]
  829. loanAccountInfoDf.loc[loanAccountInfoIndex, '近24月贷款最大逾期距离现在的月数'] = prp.getPayRcdMaxOverdueNumMonth(payRcdMaxOverdueDf,normalDf,reportTime, 24);
  830. payStatus= ["G","D","C","N","M","1","2","3","4","5","6","7"]
  831. # 贷款24期还款记录次数 剔除结清 转出 呆账
  832. payRcdTimesDf = payRcdDf[payRcdDf['账户编号'].isin(normalDf['账户编号'].values)]
  833. #从“贷款信息”中提取,剔除“账户状态”为结清、转出、呆账、呆帐后,各账户的还款次数统计“24个月(账户)还款状态”包含"G","D","C","N","M"及数字的个数,MAX(各账户的还款次数)
  834. payRcdTimesDf = payRcdTimesDf[payRcdTimesDf['还款状态'].isin(payStatus)]
  835. payRcdTimes = payRcdTimesDf.groupby(['账户编号'])['还款状态'].count()
  836. #payRcdDf[(payRcdDf['还款状态']!='') & (payRcdDf['账户编号']==1)].index.size
  837. loanAccountInfoDf.loc[loanAccountInfoIndex, '贷款24期还款记录次数'] = np.max(payRcdTimes)
  838. #解析信贷交易明细-特殊交易
  839. def parseSpecialTrade(df):
  840. if not df.empty:
  841. creditTradeDetailHeader_specialTrade.loc[specialTradeIndex, '当前用户发生特殊交易的严重程度'] = np.max(df['严重程度'])#加工的指标
  842. maxChangeMonthIndex = np.argmax(np.abs(df['变更月数']))
  843. meanMonthValue = np.mean(np.abs(df['变更月数']))
  844. row0 = df.loc[maxChangeMonthIndex, :]
  845. settleDf = df[(df['特殊交易类型']=='提前结清') | (df['特殊交易类型']=='提前还款')]
  846. debtDf = df[(df['特殊交易类型'] == '以资抵债')]
  847. creditTradeDetailHeader_specialTrade.loc[specialTradeIndex, '用户发生特殊交易变更月数的最大差值'] = row0[3]
  848. creditTradeDetailHeader_specialTrade.loc[specialTradeIndex, '用户发生特殊交易变更月数的平均差值'] = round(meanMonthValue,2)
  849. creditTradeDetailHeader_specialTrade.loc[specialTradeIndex, '用户特殊交易涉及的发生金额的最大值'] = np.max(df['发生金额'])
  850. creditTradeDetailHeader_specialTrade.loc[specialTradeIndex, '用户特殊交易涉及的发生金额的平均值'] = round(np.mean(df['发生金额']),2)
  851. creditTradeDetailHeader_specialTrade.loc[specialTradeIndex, '用户所有帐户发生提前还款交易的次数统计'] = settleDf.index.size
  852. creditTradeDetailHeader_specialTrade.loc[specialTradeIndex, '用户所有帐户发生不良特殊交易的次数统计'] = debtDf.index.size;
  853. #信贷交易明细-非循环贷账户
  854. def parseLoanAccountInfo(df):
  855. if not df.empty:
  856. loanAccountNum = int(briefInfoDf_loanTradeCreditInfo.loc[loanTradeCreditInfoIndex, '非循环贷账户账户数'])
  857. normalDf = df[(df['账户状态'] != '结清') & (df['账户状态'] != '转出') & (df['账户状态'] != '呆账')].reset_index(drop=True)
  858. normalDf = normalDf[0:loanAccountNum]#根据非循环贷账户数进行计算进行截取
  859. creditTradeDetailDf_loanAccountInfo.loc[loanInfoIndex, '本月应还款(合计)'] = np.sum(normalDf['本月应还款'])
  860. creditTradeDetailDf_loanAccountInfo.loc[loanInfoIndex, '本月实还款(合计)'] = np.sum(normalDf['本月实还款'])
  861. creditTradeDetailDf_loanAccountInfo.loc[loanInfoIndex, '最近一次还款日期'] = np.max(normalDf['最近一次还款日期'])
  862. creditTradeDetailDf_loanAccountInfo.loc[loanInfoIndex, '当前一共逾期期数'] = np.sum(normalDf['当前逾期期数'])
  863. creditTradeDetailDf_loanAccountInfo.loc[loanInfoIndex, '当前一共逾期总额'] = np.sum(normalDf['当前逾期总额'])
  864. creditTradeDetailDf_loanAccountInfo.loc[loanInfoIndex, '逾期31-60天未还本金(合计)'] = np.sum(normalDf['逾期31-60天未还本金'])
  865. creditTradeDetailDf_loanAccountInfo.loc[loanInfoIndex, '逾期61-90天未还本金(合计)'] = np.sum(normalDf['逾期61-90天未还本金'])
  866. creditTradeDetailDf_loanAccountInfo.loc[loanInfoIndex, '逾期91-180天未还本金(合计)'] = np.sum(normalDf['逾期91-180天未还本金'])
  867. creditTradeDetailDf_loanAccountInfo.loc[loanInfoIndex, '逾期180天以上未还本金(合计)']= np.sum(normalDf['逾期180天以上未还本金'])
  868. #信贷交易明细-循环额度分账户
  869. def parseCycleCreditAccountInfo(df):
  870. if not df.empty:
  871. normalDf = df[(df['账户状态'] != '结清') & (df['账户状态'] != '转出') & (df['账户状态'] != '呆账')].reset_index(drop=True)
  872. loanAccountNum = int(briefInfoDf_loanTradeCreditInfo.loc[loanTradeCreditInfoIndex, '非循环贷账户账户数'])
  873. cycleCreditAccountNum = int(briefInfoDf_loanTradeCreditInfo.loc[loanTradeCreditInfoIndex, '循环额度下分账户账户数'])
  874. normalDf = normalDf[loanAccountNum:(loanAccountNum + cycleCreditAccountNum)]
  875. if not normalDf.empty:
  876. creditTradeDetailDf_cycleCreditAccountInfo.loc[cycleCreditAccountInfoIndex, '本月应还款(合计)'] = np.sum(normalDf['本月应还款'])
  877. creditTradeDetailDf_cycleCreditAccountInfo.loc[cycleCreditAccountInfoIndex, '本月实还款(合计)'] = np.sum(normalDf['本月实还款'])
  878. creditTradeDetailDf_cycleCreditAccountInfo.loc[cycleCreditAccountInfoIndex, '最近一次还款日期'] = np.max(normalDf['最近一次还款日期'])
  879. creditTradeDetailDf_cycleCreditAccountInfo.loc[cycleCreditAccountInfoIndex, '当前一共逾期期数'] = np.sum(normalDf['当前逾期期数'])
  880. creditTradeDetailDf_cycleCreditAccountInfo.loc[cycleCreditAccountInfoIndex, '当前一共逾期总额'] = np.sum(normalDf['当前逾期总额'])
  881. creditTradeDetailDf_cycleCreditAccountInfo.loc[cycleCreditAccountInfoIndex, '逾期31-60天未还本金(合计)'] = np.sum(normalDf['逾期31-60天未还本金'])
  882. creditTradeDetailDf_cycleCreditAccountInfo.loc[cycleCreditAccountInfoIndex, '逾期61-90天未还本金(合计)'] = np.sum(normalDf['逾期61-90天未还本金'])
  883. creditTradeDetailDf_cycleCreditAccountInfo.loc[cycleCreditAccountInfoIndex, '逾期91-180天未还本金(合计)'] = np.sum(normalDf['逾期91-180天未还本金'])
  884. creditTradeDetailDf_cycleCreditAccountInfo.loc[cycleCreditAccountInfoIndex, '逾期180天以上未还本金(合计)']= np.sum(normalDf['逾期180天以上未还本金'])
  885. #信贷交易明细-循环贷账户
  886. def parseCycleLoanAccountInfo(df):
  887. if not df.empty:
  888. normalDf = df[(df['账户状态'] != '结清') & (df['账户状态'] != '转出') & (df['账户状态'] != '呆账')]
  889. loanAccountNum = int(briefInfoDf_loanTradeCreditInfo.loc[loanTradeCreditInfoIndex, '非循环贷账户账户数'])
  890. cycleCreditAccountNum = int(briefInfoDf_loanTradeCreditInfo.loc[loanTradeCreditInfoIndex, '循环额度下分账户账户数'])
  891. cycleAccountNum = int(briefInfoDf_loanTradeCreditInfo.loc[loanTradeCreditInfoIndex, '循环贷账户账户数'])
  892. normalDf = normalDf[(loanAccountNum+cycleCreditAccountNum):normalDf.index.size]
  893. if not normalDf.empty:
  894. creditTradeDetailDf_cycleLoanAccountInfo.loc[cycleLoanAccountInfoIndex, '本月应还款(合计)'] = np.sum(normalDf['本月应还款'])
  895. creditTradeDetailDf_cycleLoanAccountInfo.loc[cycleLoanAccountInfoIndex, '本月实还款(合计)'] = np.sum(normalDf['本月实还款'])
  896. creditTradeDetailDf_cycleLoanAccountInfo.loc[cycleLoanAccountInfoIndex, '最近一次还款日期'] = np.max(normalDf['最近一次还款日期'])
  897. creditTradeDetailDf_cycleLoanAccountInfo.loc[cycleLoanAccountInfoIndex, '当前一共逾期期数'] = np.sum(normalDf['当前逾期期数'])
  898. creditTradeDetailDf_cycleLoanAccountInfo.loc[cycleLoanAccountInfoIndex, '当前一共逾期总额'] = np.sum(normalDf['当前逾期总额'])
  899. creditTradeDetailDf_cycleLoanAccountInfo.loc[cycleLoanAccountInfoIndex, '逾期31-60天未还本金(合计)'] = np.sum(normalDf['逾期31-60天未还本金'])
  900. creditTradeDetailDf_cycleLoanAccountInfo.loc[cycleLoanAccountInfoIndex, '逾期61-90天未还本金(合计)'] = np.sum(normalDf['逾期61-90天未还本金'])
  901. creditTradeDetailDf_cycleLoanAccountInfo.loc[cycleLoanAccountInfoIndex, '逾期91-180天未还本金(合计)'] = np.sum(normalDf['逾期91-180天未还本金'])
  902. creditTradeDetailDf_cycleLoanAccountInfo.loc[cycleLoanAccountInfoIndex, '逾期180天以上未还本金(合计)']= np.sum(normalDf['逾期180天以上未还本金'])
  903. #解析贷款账户信息指标
  904. def parseLoanMergeDf(df):
  905. if not df.empty:
  906. sortDf = df.sort_values(by=["账户关闭日期","借款金额(本金)"] , ascending=(False,False))
  907. sortDf = sortDf[sortDf['账户状态'] == '结清'];
  908. sortDf = sortDf.reset_index(drop=True)
  909. if not sortDf.empty:
  910. row0 = sortDf.loc[0, :]
  911. loanAccountInfo["lastSettleLoanAmt"] = row0['借款金额(本金)']
  912. loanAccountInfoDf.loc[loanAccountInfoIndex, '最近一笔结清贷款的贷款金额'] = row0['借款金额(本金)']
  913. openDate = dfParser.formatDate(row0['开立日期'])
  914. loanAccountInfoDf.loc[loanAccountInfoIndex, '最近一笔结清贷款的发放距今月数'] = utils.difMonthReportTime(openDate,queryInfo["reportTime"])
  915. settleDate = dfParser.formatDate(row0['账户关闭日期'])
  916. loanAccountInfoDf.loc[loanAccountInfoIndex, '最近一笔结清贷款的结清距今月数'] = utils.difMonthReportTime(settleDate,queryInfo["reportTime"])
  917. loanAccountInfoDf.loc[loanAccountInfoIndex, '历史贷款总法人机构数'] = df['管理机构'].unique().size
  918. loanAccountInfoDf.loc[loanAccountInfoIndex, '当前同时在用的贷款机构数'] = df[df['余额(本金)']>0]['管理机构'].unique().size
  919. statusDf = df[(df['账户状态'] != '结清') & (df['账户状态'] != '转出')]
  920. bankDf = statusDf[statusDf['管理机构'].str.contains('银行')]
  921. #没有记录
  922. if statusDf.index.size==0:
  923. isNotBankCust = -1
  924. else:
  925. if bankDf.index.size >0:#有一条以上不为结清,请包含银行
  926. isNotBankCust = 1;
  927. else:
  928. isNotBankCust = 0;
  929. loanAccountInfoDf.loc[loanAccountInfoIndex, '是否有非银行贷款客户'] = isNotBankCust
  930. #最严重的五级分类
  931. # fiveType = ""
  932. # for fiveTypeTmp in consts.fiveType:
  933. # fiveTypeDf = statusDf[statusDf['五级分类']==fiveTypeTmp];
  934. # if not fiveTypeDf.empty:
  935. # fiveType = fiveTypeTmp;
  936. # break;
  937. # loanAccountInfoDf.loc[loanAccountInfoIndex, '贷款五级分类'] = fiveType
  938. #当前贷款LTV
  939. # 从“贷款信息”中提取,剔除“账户状态”为结清及转出,并剔除“账户状态”为呆账且本金余额 = 0
  940. # 的记录后,SUM(本金余额) / SUM(贷款本金)
  941. # 如本金余额为空和贷款本金为0或为空,则当条记录不计算
  942. loanLtvDf = df[(df['账户状态'] != '结清') & (df['账户状态'] != '转出') & (df['借款金额(本金)']>0) & (df['余额(本金)']!='--')]
  943. badSetDf = loanLtvDf[~((loanLtvDf['账户状态'] == '呆账') & (loanLtvDf['余额(本金)']==0))]
  944. balanceSum = np.sum(badSetDf['余额(本金)'].astype('int'))
  945. loanAmtSum = np.sum(badSetDf['借款金额(本金)'].astype('int'))
  946. if(loanAmtSum !=0):
  947. loanAccountInfoDf.loc[loanAccountInfoIndex, '当前贷款LTV'] = round(np.divide(balanceSum,loanAmtSum),2)
  948. loanAccountInfoDf.loc[loanAccountInfoIndex, '当前贷款最高LTV'] = round(np.max(np.divide(badSetDf['余额(本金)'].astype('int'), badSetDf['借款金额(本金)'].astype('int'))),2)
  949. loanAccountInfoDf.loc[loanAccountInfoIndex, '当前贷款最低LTV'] = round(np.min(np.divide(badSetDf['余额(本金)'].astype('int'), badSetDf['借款金额(本金)'].astype('int'))), 2)
  950. loanAccountInfoDf.loc[loanAccountInfoIndex, '当前贷款平均LTV'] = round(np.mean(np.divide(badSetDf['余额(本金)'].astype('int'), badSetDf['借款金额(本金)'].astype('int'))), 2)
  951. #['个人住房商业贷款','个人商用房(含商住两用)贷款','个人住房公积金贷款','房'],
  952. houseLtvList = consts.houseLtvList;
  953. # houseLtvDf = badSetDf[badSetDf['业务种类'].isin(houseLtvList)]
  954. # if not houseLtvDf.empty:
  955. # loanAccountInfoDf.loc[loanAccountInfoIndex, '当前房贷LTV'] = round(np.divide(np.sum(houseLtvDf['余额(本金)'].astype('int')),np.sum(houseLtvDf['借款金额(本金)'].astype('int'))), 2)
  956. #['个人住房贷款','个人商用房(包括商住两用)贷款']
  957. loanAccountInfoDf.loc[loanAccountInfoIndex, '当前房贷LTV'] = lip.getCurLtv(badSetDf, houseLtvList)
  958. loanAccountInfoDf.loc[loanAccountInfoIndex, '当前贷款机构数量'] = loanLtvDf['管理机构'].unique().size
  959. cardLtvList = ['个人汽车消费贷款','车']
  960. loanAccountInfoDf.loc[loanAccountInfoIndex, '当前车贷LTV'] = lip.getCurLtv(badSetDf, cardLtvList)
  961. operateLtvList = ['个人经营性贷款']
  962. loanAccountInfoDf.loc[loanAccountInfoIndex, '当前经营贷LTV'] = lip.getCurLtv(badSetDf, operateLtvList)
  963. consumeLtvList = ['其他个人消费贷款']
  964. loanAccountInfoDf.loc[loanAccountInfoIndex, '当前消费贷LTV'] = lip.getCurLtv(badSetDf, consumeLtvList)
  965. bankLtvList = ['商业银行','外资银行','村镇银行','住房储蓄银行','财务公司']
  966. loanAccountInfoDf.loc[loanAccountInfoIndex, '当前银行贷LTV'] = lip.getCurBankLtv(badSetDf, bankLtvList)
  967. bankLtvList = ['消费金融公司','汽车金融公司','信托公司']# TODO
  968. loanAccountInfoDf.loc[loanAccountInfoIndex, '当前消金贷LTV'] = lip.getCurBankLtv(badSetDf, bankLtvList)
  969. smallLoanLtvList = ['小额信贷公司']
  970. loanAccountInfoDf.loc[loanAccountInfoIndex, '当前小贷LTV'] = lip.getCurBankLtv(badSetDf, smallLoanLtvList)
  971. #当前贷款最大逾期期数
  972. # 从“贷款信息”中提取,剔除“账户状态”为结清、转出、呆账、呆帐后,MAX(每笔贷款的当前逾期期数)
  973. loanOverdueLtvDf = df[(df['账户状态'] != '结清') & (df['账户状态'] != '转出') & (df['账户状态'] != '呆账')]
  974. if not loanOverdueLtvDf.empty:
  975. loanAccountInfoDf.loc[loanAccountInfoIndex, '当前贷款最大逾期期数'] = np.max(loanOverdueLtvDf['当前逾期期数'])
  976. loanAccountInfoDf.loc[loanAccountInfoIndex, '当前贷款最大逾期金额'] = np.max(loanOverdueLtvDf['当前逾期总额'])
  977. loanOverdueLtvDf=loanOverdueLtvDf.reset_index(drop=True)
  978. maxOverdueIndex = np.argmax(loanOverdueLtvDf['当前逾期期数'])
  979. loanAccountInfoDf.loc[loanAccountInfoIndex, '当前贷款最大逾期期数对应的最大逾期金额'] = loanOverdueLtvDf.loc[maxOverdueIndex,:]['当前逾期总额']
  980. loanAccountInfoDf.loc[loanAccountInfoIndex, '近3月开户最高贷款本金'] = lip.getLastLoanAmtMax(df,queryInfo["reportTime"],3)#贷款指标加工单独放到一个文件里
  981. loanAccountInfoDf.loc[loanAccountInfoIndex, '近3月开户最低贷款本金'] = lip.getLastLoanAmtMin(df, queryInfo["reportTime"], 3)
  982. loanAccountInfoDf.loc[loanAccountInfoIndex, '近3月开户平均贷款本金'] = lip.getLastLoanAmtAvg(df, queryInfo["reportTime"], 3)
  983. loanAccountInfoDf.loc[loanAccountInfoIndex, '近6月开户最高贷款本金'] = lip.getLastLoanAmtMax(df, queryInfo["reportTime"], 6)
  984. loanAccountInfoDf.loc[loanAccountInfoIndex, '近6月开户最低贷款本金'] = lip.getLastLoanAmtMin(df, queryInfo["reportTime"], 6)
  985. loanAccountInfoDf.loc[loanAccountInfoIndex, '近6月开户平均贷款本金'] = lip.getLastLoanAmtAvg(df, queryInfo["reportTime"], 6)
  986. loanAccountInfoDf.loc[loanAccountInfoIndex, '近12月开户最高贷款本金'] = lip.getLastLoanAmtMax(df, queryInfo["reportTime"], 12)
  987. loanAccountInfoDf.loc[loanAccountInfoIndex, '近12月开户最低贷款本金'] = lip.getLastLoanAmtMin(df, queryInfo["reportTime"], 12)
  988. loanAccountInfoDf.loc[loanAccountInfoIndex, '近12月开户平均贷款本金'] = lip.getLastLoanAmtAvg(df, queryInfo["reportTime"], 12)
  989. lastLoanDf = loanOverdueLtvDf;
  990. if not lastLoanDf.empty:
  991. loanAccountInfoDf.loc[loanAccountInfoIndex, '贷款最近一次还款日期距今时长'] = lip.getLastPayDateMinDays(lastLoanDf,queryInfo["reportTime"])
  992. normalDf = df[(df['账户状态'] == '正常') & (df['当前逾期期数'] == 0)]
  993. #未结清贷款总账户数:账户状态不等于结清和转出的记录数
  994. notSettleDf = df[(df['账户状态'] != '结清') & (df['账户状态'] != '转出')]
  995. if not notSettleDf.empty:
  996. loanAccountInfoDf.loc[loanAccountInfoIndex, '当前正常贷款账户数'] = normalDf.index.size
  997. loanAccountInfoDf.loc[loanAccountInfoIndex, '当前正常贷款账户数占比'] = round(normalDf.index.size/notSettleDf.index.size,2)
  998. #当前未结清贷款余额总和
  999. # ltvDf = tmpDf[tmpDf['业务种类'].isin(bizTypeList)]
  1000. loanAccountInfoDf.loc[loanAccountInfoIndex, '当前未结清贷款余额总和'] = np.sum(notSettleDf['余额(本金)'])
  1001. loanAccountInfoDf.loc[loanAccountInfoIndex, '当前未结清贷款余额总和'] = np.sum(notSettleDf['余额(本金)'])
  1002. # 当前未结清住房贷款余额总和
  1003. houseDf = notSettleDf[notSettleDf['业务种类'].isin(houseLtvList)]
  1004. loanAccountInfoDf.loc[loanAccountInfoIndex, '当前未结清住房贷款余额总和'] = np.sum(houseDf['余额(本金)'])
  1005. # 当前未结清汽车贷款余额总和
  1006. cardDf = notSettleDf[notSettleDf['业务种类'].isin(cardLtvList)]
  1007. loanAccountInfoDf.loc[loanAccountInfoIndex, '当前未结清汽车贷款余额总和'] = np.sum(cardDf['余额(本金)'])
  1008. # 当前未结清个人经营性贷款余额总和
  1009. operateLtvDf = notSettleDf[notSettleDf['业务种类'].isin(operateLtvList)]
  1010. loanAccountInfoDf.loc[loanAccountInfoIndex, '当前未结清个人经营性贷款余额总和'] = np.sum(operateLtvDf['余额(本金)'])
  1011. # 当前平均每月贷款余额总和
  1012. loanAccountInfoDf.loc[loanAccountInfoIndex, '当前平均每月贷款余额总和'] = round(np.sum(normalDf['余额(本金)'])/12,2)
  1013. #当前正常贷款账户余额
  1014. loanAccountInfoDf.loc[loanAccountInfoIndex, '当前正常贷款账户余额'] = np.sum(normalDf['余额(本金)'])
  1015. # "从“贷款信息”中提取,剔除结清、转出,当前正常贷款账户余额/未结清贷款总余额(本金余额加总)
  1016. loanAccountInfoDf.loc[loanAccountInfoIndex, '当前正常贷款账户余额占总余额比'] = round(np.sum(normalDf['余额(本金)'])/np.sum(notSettleDf['余额(本金)']))
  1017. settleDf = df[(df['账户状态'] == '结清')]
  1018. loanAccountInfoDf.loc[loanAccountInfoIndex, '当前正常结清贷款账户数'] = settleDf.index.size
  1019. loanAccountInfoDf.loc[loanAccountInfoIndex, '当前正常结清贷款账户数占比'] = round(settleDf.index.size/df.index.size,2)
  1020. #贷款24期还款记录次数 TODO
  1021. # 最近3个月个人消费贷款发放额度
  1022. loanAccountInfoDf.loc[loanAccountInfoIndex, '贷款本月实还款金额'] = np.sum(loanOverdueLtvDf['本月应还款'])
  1023. loanAccountInfoDf.loc[loanAccountInfoIndex, '最近3个月个人消费贷款发放额度'] = lip.getLastPerConsumeAmt(df,3,queryInfo["reportTime"])
  1024. loanAccountInfoDf.loc[loanAccountInfoIndex, '最近6个月个人消费贷款发放额度'] = lip.getLastPerConsumeAmt(df, 6,queryInfo["reportTime"])
  1025. loanAccountInfoDf.loc[loanAccountInfoIndex, '最近12个月个人消费贷款发放额度'] = lip.getLastPerConsumeAmt(df, 12,queryInfo["reportTime"])
  1026. #未结清贷款平均剩余还款期数
  1027. payPieDf = notSettleDf[notSettleDf['还款期数']!='--']
  1028. if payPieDf.index.size!=0:
  1029. loanAccountInfoDf.loc[loanAccountInfoIndex, '未结清贷款平均剩余还款期数'] = round(np.sum(payPieDf['剩余还款期数'])/payPieDf.index.size,2)
  1030. # 当前贷款本月应还金额总和
  1031. loanAccountInfoDf.loc[loanAccountInfoIndex, '当前贷款本月应还金额总和'] = np.sum(notSettleDf['本月应还款'])
  1032. # 当前贷款本月实还金额总额
  1033. loanAccountInfoDf.loc[loanAccountInfoIndex, '当前贷款本月实还金额总额'] = np.sum(notSettleDf['本月实还款'])
  1034. #解析贷记卡账户信息指标
  1035. def parseCreditCardMergeDf(df):
  1036. if not df.empty:
  1037. # 历史信用卡总法人机构数
  1038. # creditCardAccountInfoDf.loc[creditCardAccountInfoIndex,'历史信用卡总法人机构数'] = df['发卡机构'].unique().size
  1039. # creditCardUseDf = df[df['已用额度']>0];
  1040. # creditCardAccountInfoDf.loc[creditCardAccountInfoIndex,'当前同时在用的信用卡机构数'] = creditCardUseDf['发卡机构'].unique().size
  1041. #统一排除
  1042. creditDf = df[(df['币种'] == '人民币元') & (df['账户状态'] != '未激活') & (df['账户状态'] != '销户') & (df['账户状态'] != '呆账')]
  1043. totalAmtDf = df[(df['币种'] == '人民币元') & (df['账户状态'] != '未激活') & (df['账户状态'] != '销户') & (df['账户状态'] != '呆账')]
  1044. #大额专项分期额度(合计)
  1045. # 已用分期金额(合计)
  1046. creditCardAccountInfoDf.loc[creditCardAccountInfoIndex, '大额专项分期额度(合计)'] = np.sum(creditDf['大额专项分期额度'])
  1047. creditCardAccountInfoDf.loc[creditCardAccountInfoIndex, '已用分期金额(合计)'] = np.sum(creditDf['已用分期金额'])
  1048. # creditCardAccountInfoDf.loc[creditCardAccountInfoIndex,'贷记卡账户当前总额度'] = cip.getMaxCreditAmt(creditDf)
  1049. creditCardAccountInfoDf.loc[creditCardAccountInfoIndex, '最近新发放的3张贷记卡平均额度'] = cip.getAvgCreditAmt(creditDf)
  1050. creditCardAccountInfoDf.loc[creditCardAccountInfoIndex, '贷记卡额度使用率超过90%的机构数占比'] = cip.getUseRate(creditDf,df,0.9)
  1051. creditCardAccountInfoDf.loc[creditCardAccountInfoIndex, '贷记卡额度使用率超过100%的机构数占比'] = cip.getUseRate(creditDf, totalAmtDf, 1)
  1052. # 从“贷记卡信息”中提取,计算授信额度时剔除销户,计算已用额度时剔除呆账、呆帐、销户后,SUM(各账户已用额度) / SUM(各账户授信额度)
  1053. useCreditDf = df[(df['币种'] == '人民币元') & (df['账户状态'] != '销户') & (df['账户状态'] != '呆账')]
  1054. totalCreditDf = df[(df['币种'] == '人民币元') & (df['账户状态'] != '销户')]
  1055. totalCreditAmt = np.sum(totalCreditDf['账户授信额度'])
  1056. if totalCreditAmt != 0:#授信额度不能为0
  1057. creditCardAccountInfoDf.loc[creditCardAccountInfoIndex, '贷记卡账户当前总额度使用率'] = round(np.sum(useCreditDf['已用额度'])/np.sum(totalCreditDf['账户授信额度']),2)
  1058. creditCardAccountInfoDf.loc[creditCardAccountInfoIndex, '贷记卡账户最高使用额度总的使用率'] = round(np.sum(useCreditDf['最大使用额']) / np.sum(totalCreditDf['账户授信额度']), 2)
  1059. creditCardAccountInfoDf.loc[creditCardAccountInfoIndex, '贷记卡账户近6月平均额度总的使用率'] = round(np.sum(useCreditDf['最近6个月平均使用额度']) / np.sum(totalCreditDf['账户授信额度']), 2)
  1060. # creditCardAccountInfoDf.loc[creditCardAccountInfoIndex, '当前贷记卡最大逾期期数'] = np.max(creditDf['当前逾期期数'])#用于计算
  1061. creditCardAccountInfoDf.loc[creditCardAccountInfoIndex, '当前贷记卡最大逾期金额'] = np.max(creditDf['当前逾期总额'])
  1062. if not creditDf.empty:
  1063. creditDf = creditDf.reset_index(drop=True)
  1064. maxOverdueIndex = np.argmax(creditDf['当前逾期期数'])
  1065. creditCardAccountInfoDf.loc[creditCardAccountInfoIndex, '当前贷记卡最大逾期期数对应的最大逾期金额'] = creditDf.loc[maxOverdueIndex,:]['当前逾期总额']
  1066. creditCardAccountInfoDf.loc[creditCardAccountInfoIndex, '近3月开卡最高额度'] = cip.getLastMonthMaxCreditAmt(df,queryInfo["reportTime"],3)
  1067. creditCardAccountInfoDf.loc[creditCardAccountInfoIndex, '近3月开卡最低额度'] = cip.getLastMonthMinCreditAmt(df, queryInfo["reportTime"], 3)
  1068. creditCardAccountInfoDf.loc[creditCardAccountInfoIndex, '近3月开卡平均额度'] = cip.getLastMonthAvgCreditAmt(df, queryInfo["reportTime"], 3)
  1069. creditCardAccountInfoDf.loc[creditCardAccountInfoIndex, '近6月开卡最高额度'] = cip.getLastMonthMaxCreditAmt(df, queryInfo["reportTime"], 6)
  1070. creditCardAccountInfoDf.loc[creditCardAccountInfoIndex, '近6月开卡最低额度'] = cip.getLastMonthMinCreditAmt(df, queryInfo["reportTime"], 6)
  1071. creditCardAccountInfoDf.loc[creditCardAccountInfoIndex, '近6月开卡平均额度'] = cip.getLastMonthAvgCreditAmt(df, queryInfo["reportTime"], 6)
  1072. creditCardAccountInfoDf.loc[creditCardAccountInfoIndex, '近12月开卡最高额度'] = cip.getLastMonthMaxCreditAmt(df, queryInfo["reportTime"], 12)
  1073. creditCardAccountInfoDf.loc[creditCardAccountInfoIndex, '近12月开卡最低额度'] = cip.getLastMonthMinCreditAmt(df, queryInfo["reportTime"], 12)
  1074. creditCardAccountInfoDf.loc[creditCardAccountInfoIndex, '近12月开卡平均额度'] = cip.getLastMonthAvgCreditAmt(df, queryInfo["reportTime"], 12)
  1075. if not creditDf.empty:
  1076. creditCardAccountInfoDf.loc[creditCardAccountInfoIndex, '贷记卡最近一次还款日期距今时长'] = cip.getLastPayDateMinDays(creditDf,queryInfo["reportTime"])
  1077. paySo = np.sum(creditDf['本月应还款'])
  1078. if(paySo)!=0:
  1079. creditCardAccountInfoDf.loc[creditCardAccountInfoIndex, '贷记卡还款比例'] = round(np.sum(creditDf['本月实还款'])/np.sum(creditDf['本月应还款']),2)
  1080. creditDfTmp = creditDf[creditDf['本月应还款']>0]
  1081. creditCardAccountInfoDf.loc[creditCardAccountInfoIndex, '贷记卡最高还款比例'] = round(np.max(np.divide(creditDfTmp['本月实还款'] , creditDfTmp['本月应还款'])), 2)
  1082. creditCardAccountInfoDf.loc[creditCardAccountInfoIndex, '贷记卡最低还款比例'] = round(np.min(np.divide(creditDfTmp['本月实还款'] , creditDfTmp['本月应还款'])), 2)
  1083. normalDf = df[(df['币种'] == '人民币元') & (df['账户状态'] == '正常') & (df['当前逾期期数']==0)];
  1084. notCloseDf = df[(df['账户状态'] != '销户')]
  1085. creditCardAccountInfoDf.loc[creditCardAccountInfoIndex, '当前正常贷记卡账户数'] = normalDf.index.size
  1086. if not notCloseDf.empty and not normalDf.empty:
  1087. creditCardAccountInfoDf.loc[creditCardAccountInfoIndex, '当前正常贷记卡账户数占比'] = round(normalDf.index.size/notCloseDf.index.size,2)
  1088. creditCardAccountInfoDf.loc[creditCardAccountInfoIndex, '当前正常贷记卡已用额度'] = np.sum(normalDf['已用额度'])
  1089. creditCardAccountInfoDf.loc[creditCardAccountInfoIndex, '当前正常且有余额的贷记卡账户数'] = normalDf[normalDf['已用额度']>0].index.size
  1090. if not creditDf.empty:
  1091. creditUseAmt = np.sum(creditDf['已用额度'])
  1092. if creditUseAmt!=0:
  1093. creditCardAccountInfoDf.loc[creditCardAccountInfoIndex, '当前正常贷记卡账户余额占总余额比'] = round(np.sum(normalDf['已用额度']) / np.sum(creditDf['已用额度']), 2)
  1094. if notCloseDf.empty:
  1095. creditCardAccountInfoDf.loc[creditCardAccountInfoIndex, '当前正常且有余额的贷记卡账户数占比'] = -99
  1096. else:
  1097. creditCardAccountInfoDf.loc[creditCardAccountInfoIndex, '当前正常且有余额的贷记卡账户数占比'] = \
  1098. round(creditCardAccountInfoDf.loc[creditCardAccountInfoIndex, '当前正常且有余额的贷记卡账户数']/notCloseDf.index.size,3)
  1099. #当前正常贷记卡账户余额占总余额比
  1100. creditCardAccountInfoDf.loc[creditCardAccountInfoIndex, '当前贷记卡本月实还金额总和'] = np.sum(creditDf['本月实还款'])
  1101. creditCardAccountInfoDf.loc[creditCardAccountInfoIndex, '当前贷记卡本月应还金额总和'] = np.sum(creditDf['本月应还款'])
  1102. maxAmtDf = df[(df['币种'] == '人民币元')]
  1103. if not maxAmtDf.empty:
  1104. maxAmtDf = maxAmtDf.reset_index(drop=True)
  1105. maxAmtIndex = np.argmax(maxAmtDf['账户授信额度'])
  1106. maxOpenDate = maxAmtDf.loc[maxAmtIndex,:]['开立日期'];
  1107. creditCardAccountInfoDf.loc[creditCardAccountInfoIndex, '额度最高的人民币贷记卡开卡距今月份数'] = utils.difMonthReportTime(maxOpenDate,queryInfo["reportTime"]);
  1108. # 名下贷记卡数量-状态正常
  1109. creditCardAccountInfoDf.loc[creditCardAccountInfoIndex, '名下贷记卡数量-状态正常'] = df[(df['账户状态'] != '销户')].index.size
  1110. # 名下贷记卡数量-状态未激活
  1111. creditCardAccountInfoDf.loc[creditCardAccountInfoIndex, '名下贷记卡数量-状态未激活'] = df[(df['账户状态'] == '未激活')].index.size
  1112. # 名下贷记卡数量-状态异常--异常包含(2-冻结,3-止付,5-呆帐,10-其他)
  1113. abnormalList = ['冻结','止付','呆帐','其他']
  1114. creditCardAccountInfoDf.loc[creditCardAccountInfoIndex, '名下贷记卡数量-状态异常'] = df[(df['账户状态'].isin(abnormalList))].index.size
  1115. # 名下贷记卡比例-状态正常
  1116. creditCardAccountInfoDf.loc[creditCardAccountInfoIndex, '名下贷记卡比例-状态正常'] = round(creditCardAccountInfoDf.loc[creditCardAccountInfoIndex, '名下贷记卡数量-状态正常'] / df.index.size,2)
  1117. # 名下贷记卡比例-状态未激活
  1118. creditCardAccountInfoDf.loc[creditCardAccountInfoIndex, '名下贷记卡比例-状态未激活'] =round(creditCardAccountInfoDf.loc[creditCardAccountInfoIndex, '名下贷记卡数量-状态未激活'] / df.index.size,2)
  1119. # 名下贷记卡比例-状态异常
  1120. creditCardAccountInfoDf.loc[creditCardAccountInfoIndex, '名下贷记卡比例-状态异常'] = round(creditCardAccountInfoDf.loc[creditCardAccountInfoIndex, '名下贷记卡数量-状态异常'] / df.index.size,2)
  1121. #解析准贷记卡账户信息指标
  1122. def parseCreditCardMergeDfZ(df,payRcd):
  1123. if not df.empty:
  1124. overdueCreditCardRcdDf = payRcd[payRcd['账户编号'].isin(df['账户编号'].values)];
  1125. overdueCreditCardRcdDf = utils.replacePayRcdStatusOverdue(overdueCreditCardRcdDf)
  1126. creditCardAccountInfoDfZ.loc[creditCardAccountInfoIndexZ, '本月应还款(合计)'] = np.nansum(df['透支余额'])
  1127. creditCardAccountInfoDfZ.loc[creditCardAccountInfoIndexZ, '本月实还款(合计)'] = np.nansum(df['本月实还款'])
  1128. creditCardAccountInfoDfZ.loc[creditCardAccountInfoIndexZ, '最近一次还款日期'] = np.max(df['最近一次还款日期'])
  1129. creditCardAccountInfoDfZ.loc[creditCardAccountInfoIndexZ, '当前一共透支期数'] = cip.getCurOverdueNum(overdueCreditCardRcdDf);
  1130. creditCardAccountInfoDfZ.loc[creditCardAccountInfoIndexZ, '当前一共透支总额'] = np.nansum(df['透支余额'])
  1131. creditCardAccountInfoDfZ.loc[creditCardAccountInfoIndexZ, '透支180天以上未支付余额(合计)'] = np.nansum(df['透支180天以上未付余额'])
  1132. creditDf = df[(df['账户状态'] != '未激活') & (df['账户状态'] != '销户')]
  1133. if not creditDf.empty:
  1134. totalAmt = np.nansum(creditDf['账户授信额度'])
  1135. creditAmt = np.nansum(creditDf['透支余额'])
  1136. if totalAmt !=0:
  1137. #从“贷记卡信息”中提取,剔除未激活、销户后,所有账户透支金额/所有账户账户授信额度。
  1138. creditCardAccountInfoDfZ.loc[creditCardAccountInfoIndexZ, '全部准贷记卡账户当前总额度使用率']=round(creditAmt/totalAmt,2)
  1139. #从“贷记卡信息”中提取,剔除未激活、销户后,MAX(单账户最高透支金额/单账户授信额度)
  1140. creditMaxDf = creditDf[creditDf['账户授信额度']>0]
  1141. if not creditMaxDf.empty:
  1142. creditMaxDf = creditMaxDf.fillna(0.0)
  1143. creditCardAccountInfoDfZ.loc[creditCardAccountInfoIndexZ, '准贷记卡账户最高使用额度总的使用率'] = round(np.max(np.divide(creditMaxDf['最大透支余额'],creditMaxDf['账户授信额度'])),2)
  1144. creditMaxDf = creditDf[creditDf['最大透支余额'] > 0]
  1145. if not creditMaxDf.empty:
  1146. creditCardAccountInfoDfZ.loc[creditCardAccountInfoIndexZ, '当前准贷记卡最大透支金额'] = np.max(creditMaxDf['最大透支余额'])
  1147. #从“贷记卡信息”中提取,剔除未激活、销户后,当前透支准贷记卡账户数/总准贷记卡账户数,透支账户判断:透支余额不为0的账户
  1148. creditDfTmp = creditDf[creditDf['透支余额']>0]
  1149. creditCardAccountInfoDfZ.loc[creditCardAccountInfoIndexZ, '当前准贷记卡透支账户数占比'] = round(creditDfTmp.index.size / creditDf.index.size,2)
  1150. creditCardAccountInfoDfZ.loc[creditCardAccountInfoIndexZ, '当前准贷记卡本月应还金额总和'] = np.nansum(df['透支余额'])
  1151. creditCardAccountInfoDfZ.loc[creditCardAccountInfoIndexZ, '当前准贷记卡本月实还金额总和'] = np.nansum(df['本月实还款'])
  1152. #解析使用率 TODO 使用汇总计算还是使用明细计算
  1153. def parseUseRate():
  1154. # useRateDf.loc[useRateIndex, '贷记卡账户使用率(已用额度/授信总额)']
  1155. # 从“信贷交易授信及负债信息概要”中“非循环贷账户信息汇总”、“循环额度下分账户信息汇总”、“循环贷账户信息汇总”、“贷记卡账户信息汇总”和“准贷记卡账户信息汇总”里提取,SUM(
  1156. # 所有“余额”、“已用额度”和“透支余额”) / SUM(所有“授信总额”和“授信额度”)
  1157. loanUseAmt = briefInfoDf_loanTradeCreditInfo.loc[loanTradeCreditInfoIndex, '非循环贷账户余额']
  1158. cycleCreditUseAmt = briefInfoDf_loanTradeCreditInfo.loc[loanTradeCreditInfoIndex, '循环额度下分账户余额']
  1159. cycleUseAmt = briefInfoDf_loanTradeCreditInfo.loc[loanTradeCreditInfoIndex, '循环贷账户余额']
  1160. creditUseAmt = briefInfoDf_loanTradeCreditInfo.loc[loanTradeCreditInfoIndex, '贷记卡已用额度']
  1161. creditAmtUseZ = briefInfoDf_loanTradeCreditInfo.loc[loanTradeCreditInfoIndex, '准贷记卡已用额度']
  1162. loanTotalAmt = briefInfoDf_loanTradeCreditInfo.loc[loanTradeCreditInfoIndex, '非循环贷账户授信总额']
  1163. cycleCreditTotalAmt = briefInfoDf_loanTradeCreditInfo.loc[loanTradeCreditInfoIndex, '循环额度下分账户授信总额']
  1164. cycleTotalAmt = briefInfoDf_loanTradeCreditInfo.loc[loanTradeCreditInfoIndex, '循环贷账户授信总额']
  1165. creditTotalAmt = briefInfoDf_loanTradeCreditInfo.loc[loanTradeCreditInfoIndex, '贷记卡授信总额']
  1166. creditAmtTotalZ = briefInfoDf_loanTradeCreditInfo.loc[loanTradeCreditInfoIndex, '准贷记卡授信总额']
  1167. # if str(loanUseAmt)=="nan":
  1168. # loanUseAmt = 0;
  1169. # if str(cycleCreditUseAmt) == "nan":
  1170. # loanUseAmt = 0;
  1171. # if str(cycleCreditUseAmt) == "nan":
  1172. # loanUseAmt = 0;
  1173. useAmt = loanUseAmt+cycleCreditUseAmt+cycleUseAmt+creditUseAmt+creditAmtUseZ
  1174. totalAmt = loanTotalAmt+cycleCreditTotalAmt+cycleTotalAmt+creditTotalAmt+creditAmtTotalZ
  1175. if totalAmt !=0:
  1176. useRateDf.loc[useRateIndex, '全账户使用率(已用额度/授信总额)'] = round(useAmt / totalAmt,2)
  1177. if loanTotalAmt!=0:
  1178. useRateDf.loc[useRateIndex, '非循环贷账户使用率(已用额度/授信总额)'] = round(loanUseAmt / loanTotalAmt,2)
  1179. if cycleCreditTotalAmt !=0:
  1180. useRateDf.loc[useRateIndex, '循环额度下分账户使用率(已用额度/授信总额)'] = round(cycleCreditTotalAmt / cycleCreditTotalAmt,2)
  1181. if cycleTotalAmt !=0:
  1182. useRateDf.loc[useRateIndex, '循环贷账户使用率(已用额度/授信总额)'] = round(cycleUseAmt / cycleTotalAmt,2)
  1183. if creditTotalAmt !=0:
  1184. useRateDf.loc[useRateIndex, '贷记卡账户使用率(已用额度/授信总额)'] = round(creditUseAmt / creditTotalAmt,2)
  1185. if creditAmtTotalZ !=0:
  1186. useRateDf.loc[useRateIndex, '准贷记卡账户使用率(已用额度/授信总额)'] = round(creditAmtUseZ / creditAmtTotalZ,2)
  1187. #解析开户数
  1188. def parseOpenAccount(loanDf,creditCardDf,creditCardDfZ,recoveryInfoMergeDf,loanPayRecordMergeDf,creditCardPayRecordMergeDf,creditCardPayRecordMergeDfZ):
  1189. reportTime = queryInfo["reportTime"];
  1190. openAccountDf.loc[openAccountIndex, '近3个月全账户开户数'] = cip.getOpenAccount(loanDf,reportTime,3)+cip.getOpenAccount(creditCardDf,reportTime,3)+cip.getOpenAccount(creditCardDfZ,reportTime,3)
  1191. openAccountDf.loc[openAccountIndex, '近6个月全账户开户数'] = cip.getOpenAccount(loanDf,reportTime,6)+cip.getOpenAccount(creditCardDf,reportTime,6)+cip.getOpenAccount(creditCardDfZ,reportTime,6)
  1192. openAccountDf.loc[openAccountIndex, '近9个月全账户开户数'] = cip.getOpenAccount(loanDf,reportTime,9)+cip.getOpenAccount(creditCardDf,reportTime,9)+cip.getOpenAccount(creditCardDfZ,reportTime,9)
  1193. openAccountDf.loc[openAccountIndex, '近12个月全账户开户数'] = cip.getOpenAccount(loanDf,reportTime,12)+cip.getOpenAccount(creditCardDf,reportTime,12)+cip.getOpenAccount(creditCardDfZ,reportTime,12)
  1194. openAccountDf.loc[openAccountIndex, '近24个月全账户开户数'] = cip.getOpenAccount(loanDf,reportTime,24)+cip.getOpenAccount(creditCardDf,reportTime,24)+cip.getOpenAccount(creditCardDfZ,reportTime,24)
  1195. openAccountDf.loc[openAccountIndex, '近3个月消费金融类账户开户数'] = lip.getOpenAccount(loanDf,reportTime,3,consts.bankList)
  1196. openAccountDf.loc[openAccountIndex, '近6个月消费金融类账户开户数'] = lip.getOpenAccount(loanDf,reportTime,6,consts.bankList)
  1197. openAccountDf.loc[openAccountIndex, '近9个月消费金融类账户开户数'] = lip.getOpenAccount(loanDf,reportTime,9,consts.bankList)
  1198. openAccountDf.loc[openAccountIndex, '近12个月消费金融类账户开户数'] = lip.getOpenAccount(loanDf,reportTime,12,consts.bankList)
  1199. openAccountDf.loc[openAccountIndex, '近24个月消费金融类账户开户数'] = lip.getOpenAccount(loanDf,reportTime,24,consts.bankList)
  1200. openAccountDf.loc[openAccountIndex, '近3个月贷款账户开户数'] = lip.getOpenAccount(loanDf,reportTime,3,"")
  1201. openAccountDf.loc[openAccountIndex, '近6个月贷款账户开户数'] = lip.getOpenAccount(loanDf,reportTime,6,"")
  1202. openAccountDf.loc[openAccountIndex, '近9个月贷款账户开户数'] = lip.getOpenAccount(loanDf,reportTime,9,"")
  1203. openAccountDf.loc[openAccountIndex, '近12个月贷款账户开户数'] = lip.getOpenAccount(loanDf,reportTime,12,"")
  1204. openAccountDf.loc[openAccountIndex, '近24个月贷款账户开户数'] = lip.getOpenAccount(loanDf,reportTime,24,"")
  1205. openAccountDf.loc[openAccountIndex, '近3个月贷记卡账户开户数'] = cip.getOpenAccount(creditCardDf,reportTime,3)
  1206. openAccountDf.loc[openAccountIndex, '近6个月贷记卡账户开户数'] = cip.getOpenAccount(creditCardDf,reportTime,6)
  1207. openAccountDf.loc[openAccountIndex, '近9个月贷记卡账户开户数'] = cip.getOpenAccount(creditCardDf,reportTime,9)
  1208. openAccountDf.loc[openAccountIndex, '近12个月贷记卡账户开户数'] = cip.getOpenAccount(creditCardDf,reportTime,12)
  1209. openAccountDf.loc[openAccountIndex, '近24个月贷记卡账户开户数'] = cip.getOpenAccount(creditCardDf,reportTime,24)
  1210. openAccountDf.loc[openAccountIndex, '近3个月准贷记卡账户开户数'] = cip.getOpenAccount(creditCardDfZ,reportTime,3)
  1211. openAccountDf.loc[openAccountIndex, '近6个月准贷记卡账户开户数'] = cip.getOpenAccount(creditCardDfZ,reportTime,6)
  1212. openAccountDf.loc[openAccountIndex, '近9个月准贷记卡账户开户数'] = cip.getOpenAccount(creditCardDfZ,reportTime,9)
  1213. openAccountDf.loc[openAccountIndex, '近12个月准贷记卡账户开户数'] = cip.getOpenAccount(creditCardDfZ,reportTime,12)
  1214. openAccountDf.loc[openAccountIndex, '近24个月准贷记卡账户开户数'] = cip.getOpenAccount(creditCardDfZ,reportTime,24)
  1215. #从“信贷交易信息明细”中“非循环贷账户”、“循环额度下分账户”、“循环贷账户”、“贷记卡账户”和“准贷记卡账户”里提取,5年里账户还款状态出现“1、2、3、4、5、6、7、D、Z、G、B”的账户数/所有账户数
  1216. overdueLoanPayRcdDf = loanPayRecordMergeDf[loanPayRecordMergeDf['账户编号'].isin(loanDf['账户编号'].values)]
  1217. overdueLoanPayRcdDf = utils.replacePayRcdStatusOverdue(overdueLoanPayRcdDf)
  1218. overdueLoanPayRcdDf = overdueLoanPayRcdDf[overdueLoanPayRcdDf['还款状态'] > 0]
  1219. overdueCreditPayRcdDf = creditCardPayRecordMergeDf[creditCardPayRecordMergeDf['账户编号'].isin(creditCardDf['账户编号'].values)]
  1220. overdueCreditPayRcdDf = utils.replacePayRcdStatusOverdue(overdueCreditPayRcdDf)
  1221. overdueCreditPayRcdDf = overdueCreditPayRcdDf[overdueCreditPayRcdDf['还款状态'] > 0]
  1222. overdueCreditPayRcdDfZ = creditCardPayRecordMergeDfZ[creditCardPayRecordMergeDfZ['账户编号'].isin(creditCardDfZ['账户编号'].values)]
  1223. overdueCreditPayRcdDfZ = utils.replacePayRcdStatusOverdue(overdueCreditPayRcdDfZ)
  1224. overdueCreditPayRcdDfZ = overdueCreditPayRcdDfZ[overdueCreditPayRcdDfZ['还款状态'] > 0]
  1225. loanAccountNum = loanPayRecordMergeDf['账户编号'].unique().size
  1226. creditAccountNum = creditCardPayRecordMergeDf['账户编号'].unique().size
  1227. creditAccountNumZ = creditCardPayRecordMergeDfZ['账户编号'].unique().size
  1228. overdueLoanNum = overdueLoanPayRcdDf['账户编号'].unique().size
  1229. overdueCreditNum = overdueCreditPayRcdDf['账户编号'].unique().size
  1230. overdueCreditNumZ = overdueCreditPayRcdDfZ['账户编号'].unique().size
  1231. if (loanAccountNum+creditAccountNum+creditAccountNumZ) >0:
  1232. openAccountDf.loc[openAccountIndex, '有过逾期记录的账户/全账户数'] = round((overdueLoanNum+overdueCreditNum+overdueCreditNumZ)/(loanAccountNum+creditAccountNum+creditAccountNumZ),2)
  1233. otherPerLoanDf = loanDf[loanDf['业务种类'].isin(consts.otherPerLoan)]
  1234. otherPerLoanNum = otherPerLoanDf.index.size;
  1235. overdueOtherPerLoanNum = otherPerLoanDf[otherPerLoanDf['账户编号'].isin(overdueLoanPayRcdDf['账户编号'].values)].index.size;
  1236. if otherPerLoanNum!=0:
  1237. openAccountDf.loc[openAccountIndex, '有过逾期记录的消费金融类账户/全消费金融类账户数'] = round(overdueOtherPerLoanNum/otherPerLoanNum,2)
  1238. if loanAccountNum!=0:
  1239. openAccountDf.loc[openAccountIndex, '有过逾期记录的贷款账户/全贷款账户数'] = round(overdueLoanNum/loanAccountNum,2)
  1240. if creditAccountNum!=0:
  1241. openAccountDf.loc[openAccountIndex, '有过逾期记录的贷记卡账户/全贷记卡账户数'] = round(overdueCreditNum/creditAccountNum,2)
  1242. if creditAccountNumZ!=0:
  1243. openAccountDf.loc[openAccountIndex, '有过透支记录的准贷记卡账户/全准贷记卡账户数']= round(overdueCreditNumZ/creditAccountNumZ,2)
  1244. #解析24期还款状态指标
  1245. def parsePayRcdStatus(loanMergeDf, creditCardMergeDf, creditCardMergeDfZ,loanPayRecordMergeDf,creditCardPayRecordMergeDf,creditCardPayRecordMergeDfZ):
  1246. #creditCardPayRecordMergeDf
  1247. # 去掉外币
  1248. creditCardMergeDf = creditCardMergeDf[creditCardMergeDf['币种']=='人民币元']
  1249. creditCardPayRecordMergeDf = creditCardPayRecordMergeDf[creditCardPayRecordMergeDf['账户编号'].isin(creditCardMergeDf['账户编号'].values)]
  1250. reportTime = queryInfo["reportTime"];
  1251. payRcdStatusDf.loc[payRcdStatusIndex, '贷款账户近3月逾期期数大于或等于“1”的次数'] = prp.getLoanOverdueTimes(loanPayRecordMergeDf,reportTime,1,3)
  1252. payRcdStatusDf.loc[payRcdStatusIndex, '贷款账户近6月逾期期数大于或等于“1”的次数'] = prp.getLoanOverdueTimes(loanPayRecordMergeDf,reportTime,1,6)
  1253. payRcdStatusDf.loc[payRcdStatusIndex, '贷款账户近12月逾期期数大于或等于“1”的次数'] = prp.getLoanOverdueTimes(loanPayRecordMergeDf,reportTime,1,12)
  1254. payRcdStatusDf.loc[payRcdStatusIndex, '贷款账户近24月逾期期数大于或等于“1”的次数'] = prp.getLoanOverdueTimes(loanPayRecordMergeDf,reportTime,1,24)
  1255. payRcdStatusDf.loc[payRcdStatusIndex, '贷款账户近6月逾期期数大于或等于“2”的次数'] = prp.getLoanOverdueTimes(loanPayRecordMergeDf,reportTime,2,6)
  1256. payRcdStatusDf.loc[payRcdStatusIndex, '贷款账户近12月逾期期数大于或等于“2”的次数'] = prp.getLoanOverdueTimes(loanPayRecordMergeDf,reportTime,2,12)
  1257. payRcdStatusDf.loc[payRcdStatusIndex, '贷款账户近24月逾期期数大于或等于“2”的次数'] = prp.getLoanOverdueTimes(loanPayRecordMergeDf,reportTime,2,24)
  1258. payRcdStatusDf.loc[payRcdStatusIndex, '贷款账户近6月逾期期数大于或等于“3”的次数'] = prp.getLoanOverdueTimes(loanPayRecordMergeDf,reportTime,3,6)
  1259. payRcdStatusDf.loc[payRcdStatusIndex, '贷款账户近12月逾期期数大于或等于“3”的次数'] = prp.getLoanOverdueTimes(loanPayRecordMergeDf,reportTime,3,12)
  1260. payRcdStatusDf.loc[payRcdStatusIndex, '贷款账户近24月逾期期数大于或等于“3”的次数'] = prp.getLoanOverdueTimes(loanPayRecordMergeDf,reportTime,3,24)
  1261. payRcdStatusDf.loc[payRcdStatusIndex, '贷款账户近12月逾期期数大于或大等于“4”的次数'] = prp.getLoanOverdueTimes(loanPayRecordMergeDf,reportTime,4,12)
  1262. payRcdStatusDf.loc[payRcdStatusIndex, '贷款账户近24月逾期期数大于或等于“4”的次数'] = prp.getLoanOverdueTimes(loanPayRecordMergeDf,reportTime,4,24)
  1263. payRcdStatusDf.loc[payRcdStatusIndex, '贷记卡账户近3月逾期期数大于或等于“1”的次数'] = cip.getLoanOverdueTimes(creditCardPayRecordMergeDf,reportTime,1,3)
  1264. payRcdStatusDf.loc[payRcdStatusIndex, '贷记卡账户近6月逾期期数大于或等于“1”的次数'] = cip.getLoanOverdueTimes(creditCardPayRecordMergeDf,reportTime,1,6)
  1265. payRcdStatusDf.loc[payRcdStatusIndex, '贷记卡账户近12月逾期期数大于或等于“1”的次数'] = cip.getLoanOverdueTimes(creditCardPayRecordMergeDf,reportTime,1,12)
  1266. payRcdStatusDf.loc[payRcdStatusIndex, '贷记卡账户近24月逾期期数大于或等于“1”的次数'] = cip.getLoanOverdueTimes(creditCardPayRecordMergeDf,reportTime,1,24)
  1267. payRcdStatusDf.loc[payRcdStatusIndex, '贷记卡账户近6月逾期期数大于或等于“2”的次数'] = cip.getLoanOverdueTimes(creditCardPayRecordMergeDf,reportTime,2,6)
  1268. payRcdStatusDf.loc[payRcdStatusIndex, '贷记卡账户近12月逾期期数大于或等于“2”的次数'] = cip.getLoanOverdueTimes(creditCardPayRecordMergeDf,reportTime,2,12)
  1269. payRcdStatusDf.loc[payRcdStatusIndex, '贷记卡账户近24月逾期期数大于或等于“2”的次数'] = cip.getLoanOverdueTimes(creditCardPayRecordMergeDf,reportTime,2,24)
  1270. payRcdStatusDf.loc[payRcdStatusIndex, '贷记卡账户近6月逾期期数大于或等于“3”的次数'] = cip.getLoanOverdueTimes(creditCardPayRecordMergeDf,reportTime,3,6)
  1271. payRcdStatusDf.loc[payRcdStatusIndex, '贷记卡账户近12月逾期期数大于或等于“3”的次数'] = cip.getLoanOverdueTimes(creditCardPayRecordMergeDf,reportTime,3,12)
  1272. payRcdStatusDf.loc[payRcdStatusIndex, '贷记卡账户近24月逾期期数大于或等于“3”的次数'] = cip.getLoanOverdueTimes(creditCardPayRecordMergeDf,reportTime,3,24)
  1273. payRcdStatusDf.loc[payRcdStatusIndex, '贷记卡账户近12月逾期期数大于或等于“4”的次数'] = cip.getLoanOverdueTimes(creditCardPayRecordMergeDf,reportTime,4,12)
  1274. payRcdStatusDf.loc[payRcdStatusIndex, '贷记卡账户近24月逾期期数大于或等于“4”的次数'] = cip.getLoanOverdueTimes(creditCardPayRecordMergeDf,reportTime,4,24)
  1275. payRcdStatusDf.loc[payRcdStatusIndex, '准贷记卡账户近6月逾期期数大于或等于“3”的次数'] = cip.getLoanOverdueTimes(creditCardPayRecordMergeDfZ,reportTime,3,6)
  1276. payRcdStatusDf.loc[payRcdStatusIndex, '准贷记卡账户近12月逾期期数大于或等于“3”的次数'] = cip.getLoanOverdueTimes(creditCardPayRecordMergeDfZ,reportTime,3,12)
  1277. payRcdStatusDf.loc[payRcdStatusIndex, '准贷记卡账户近24月逾期期数大于或等于“3”的次数'] = cip.getLoanOverdueTimes(creditCardPayRecordMergeDfZ,reportTime,3,24)
  1278. payRcdStatusDf.loc[payRcdStatusIndex, '准贷记卡账户近6月逾期期数大于或等于“4”的次数'] = cip.getLoanOverdueTimes(creditCardPayRecordMergeDfZ,reportTime,4,6)
  1279. payRcdStatusDf.loc[payRcdStatusIndex, '准贷记卡账户近12月逾期期数大于或等于“4”的次数'] = cip.getLoanOverdueTimes(creditCardPayRecordMergeDfZ,reportTime,4,12)
  1280. payRcdStatusDf.loc[payRcdStatusIndex, '准贷记卡账户近24月逾期期数大于或等于“4”的次数'] = cip.getLoanOverdueTimes(creditCardPayRecordMergeDfZ,reportTime,4,24)
  1281. payRcdStatusDf.loc[payRcdStatusIndex, '全账户近3月逾期期数大于或等于“1”的次数'] = prp.getLoanOverdueTimes(loanPayRecordMergeDf,reportTime,1,3)\
  1282. +cip.getLoanOverdueTimes(creditCardPayRecordMergeDf,reportTime,1,3)+cip.getLoanOverdueTimes(creditCardPayRecordMergeDfZ,reportTime,1,3)
  1283. payRcdStatusDf.loc[payRcdStatusIndex, '全账户近6月逾期期数大于或等于“1”的次数'] = \
  1284. prp.getLoanOverdueTimes(loanPayRecordMergeDf,reportTime,1,6)+cip.getLoanOverdueTimes(creditCardPayRecordMergeDf,reportTime,1,6)\
  1285. +cip.getLoanOverdueTimes(creditCardPayRecordMergeDfZ,reportTime,1,6)
  1286. payRcdStatusDf.loc[payRcdStatusIndex, '全账户近12月逾期期数大于或等于“1”的次数'] = \
  1287. prp.getLoanOverdueTimes(loanPayRecordMergeDf,reportTime,1,12)+cip.getLoanOverdueTimes(creditCardPayRecordMergeDf,reportTime,1,12)\
  1288. +cip.getLoanOverdueTimes(creditCardPayRecordMergeDfZ,reportTime,1,12)
  1289. payRcdStatusDf.loc[payRcdStatusIndex, '全账户近24月逾期期数大于或等于“1”的次数'] = \
  1290. prp.getLoanOverdueTimes(loanPayRecordMergeDf,reportTime,1,24)+cip.getLoanOverdueTimes(creditCardPayRecordMergeDf,reportTime,1,24)\
  1291. +cip.getLoanOverdueTimes(creditCardPayRecordMergeDfZ,reportTime,1,24)
  1292. payRcdStatusDf.loc[payRcdStatusIndex, '全账户近6月逾期期数大于或等于“2”的次数'] = \
  1293. prp.getLoanOverdueTimes(loanPayRecordMergeDf,reportTime,2,6)+cip.getLoanOverdueTimes(creditCardPayRecordMergeDf,reportTime,2,6)\
  1294. +cip.getLoanOverdueTimes(creditCardPayRecordMergeDfZ,reportTime,2,6)
  1295. payRcdStatusDf.loc[payRcdStatusIndex, '全账户近12月逾期期数大于或等于“2”的次数'] = \
  1296. prp.getLoanOverdueTimes(loanPayRecordMergeDf,reportTime,2,12)+cip.getLoanOverdueTimes(creditCardPayRecordMergeDf,reportTime,2,12)\
  1297. +cip.getLoanOverdueTimes(creditCardPayRecordMergeDfZ,reportTime,2,12)
  1298. payRcdStatusDf.loc[payRcdStatusIndex, '全账户近24月逾期期数大于或等于“2”的次数'] = \
  1299. prp.getLoanOverdueTimes(loanPayRecordMergeDf,reportTime,2,24)+cip.getLoanOverdueTimes(creditCardPayRecordMergeDf,reportTime,2,24)\
  1300. +cip.getLoanOverdueTimes(creditCardPayRecordMergeDfZ,reportTime,2,24)
  1301. payRcdStatusDf.loc[payRcdStatusIndex, '全账户近6月逾期期数大于或等于“3”的次数'] = \
  1302. prp.getLoanOverdueTimes(loanPayRecordMergeDf,reportTime,3,6)+cip.getLoanOverdueTimes(creditCardPayRecordMergeDf,reportTime,3,6)\
  1303. +cip.getLoanOverdueTimes(creditCardPayRecordMergeDfZ,reportTime,3,6)
  1304. payRcdStatusDf.loc[payRcdStatusIndex, '全账户近12月逾期期数大于或等于“3”的次数'] = \
  1305. prp.getLoanOverdueTimes(loanPayRecordMergeDf,reportTime,3,12)+cip.getLoanOverdueTimes(creditCardPayRecordMergeDf,reportTime,3,12)\
  1306. +cip.getLoanOverdueTimes(creditCardPayRecordMergeDfZ,reportTime,3,12)
  1307. payRcdStatusDf.loc[payRcdStatusIndex, '全账户近24月逾期期数大于或等于“3”的次数'] = \
  1308. prp.getLoanOverdueTimes(loanPayRecordMergeDf,reportTime,3,24)+cip.getLoanOverdueTimes(creditCardPayRecordMergeDf,reportTime,3,24)\
  1309. +cip.getLoanOverdueTimes(creditCardPayRecordMergeDfZ,reportTime,3,24)
  1310. payRcdStatusDf.loc[payRcdStatusIndex, '全账户近12月逾期期数大于或等于“4”的次数'] = \
  1311. prp.getLoanOverdueTimes(loanPayRecordMergeDf,reportTime,4,12)+cip.getLoanOverdueTimes(creditCardPayRecordMergeDf,reportTime,4,12)\
  1312. +cip.getLoanOverdueTimes(creditCardPayRecordMergeDfZ,reportTime,4,12)
  1313. payRcdStatusDf.loc[payRcdStatusIndex, '全账户近24月逾期期数大于或等于“4”的次数'] = \
  1314. prp.getLoanOverdueTimes(loanPayRecordMergeDf,reportTime,4,24)+cip.getLoanOverdueTimes(creditCardPayRecordMergeDf,reportTime,4,24)\
  1315. +cip.getLoanOverdueTimes(creditCardPayRecordMergeDfZ,reportTime,4,24)
  1316. payRcdStatusDf.loc[payRcdStatusIndex, '贷款账户近24个月是否出现"G"'] = prp.isExistsInd(loanPayRecordMergeDf,reportTime,"G",24)
  1317. payRcdStatusDf.loc[payRcdStatusIndex, '贷记卡账户近24个月是否出现"G"'] = prp.isExistsInd(creditCardPayRecordMergeDf,reportTime,"G",24)
  1318. payRcdStatusDf.loc[payRcdStatusIndex, '准贷记卡账户近24个月是否出现"G"'] = prp.isExistsInd(creditCardPayRecordMergeDfZ,reportTime,"G",24)
  1319. payRcdStatusDf.loc[payRcdStatusIndex, '贷款账户近24个月是否出现"Z"'] = prp.isExistsInd(loanPayRecordMergeDf,reportTime,"Z",24)
  1320. payRcdStatusDf.loc[payRcdStatusIndex, '用户所有贷款账户过去24个月存在逾期的账户数目'] = prp.getLoanOverdueCount(loanPayRecordMergeDf,reportTime,24)
  1321. payRcdStatusDf.loc[payRcdStatusIndex, '用户所有贷款账户过去24个月状态正常账户数目'] = prp.getLoanNormalCount(loanPayRecordMergeDf,reportTime,24)
  1322. payRcdStatusDf.loc[payRcdStatusIndex, '用户所有贷记卡账户过去24个月存在逾期的账户数目'] = prp.getLoanOverdueCount(creditCardPayRecordMergeDf,reportTime,24)
  1323. payRcdStatusDf.loc[payRcdStatusIndex, '用户所有贷记卡账户过去24个月状态正常的账户数目'] = prp.getLoanNormalCount(creditCardPayRecordMergeDf,reportTime,24)
  1324. payRcdStatusDf.loc[payRcdStatusIndex, '用户所有准贷记卡账户过去24个月存在逾期的账户数目'] = prp.getLoanOverdueCount(creditCardPayRecordMergeDfZ,reportTime,24)
  1325. payRcdStatusDf.loc[payRcdStatusIndex, '用户所有准贷记卡账户过去24个月状态正常的账户数目'] = prp.getLoanNormalCount(creditCardPayRecordMergeDfZ,reportTime,24)
  1326. payRcdStatusDf.loc[payRcdStatusIndex, '用户过去3个月最大逾期期数'] = prp.getPayRcdMaxOverdueNumAllAccout(loanPayRecordMergeDf,creditCardPayRecordMergeDf,creditCardPayRecordMergeDfZ,reportTime,3)
  1327. payRcdStatusDf.loc[payRcdStatusIndex, '用户过去6个月最大逾期期数'] = prp.getPayRcdMaxOverdueNumAllAccout(loanPayRecordMergeDf,creditCardPayRecordMergeDf,creditCardPayRecordMergeDfZ,reportTime,6)
  1328. payRcdStatusDf.loc[payRcdStatusIndex, '用户过去12个月最大逾期期数'] = prp.getPayRcdMaxOverdueNumAllAccout(loanPayRecordMergeDf,creditCardPayRecordMergeDf,creditCardPayRecordMergeDfZ,reportTime,12)
  1329. payRcdStatusDf.loc[payRcdStatusIndex, '用户过去24个月最大逾期期数'] = prp.getPayRcdMaxOverdueNumAllAccout(loanPayRecordMergeDf,creditCardPayRecordMergeDf,creditCardPayRecordMergeDfZ,reportTime,24)
  1330. #概要信息里的字段,从还款状态计算
  1331. briefInfoDf_overdueInfoSum.loc[overdueInfoSumIndex, '该用户过去5年出现逾期的所有账户数目'] = \
  1332. prp.getLoanOverdueCount(loanPayRecordMergeDf,reportTime,24*5)+prp.getLoanOverdueCount(creditCardPayRecordMergeDf,reportTime,24*5)\
  1333. +prp.getLoanOverdueCount(creditCardPayRecordMergeDfZ,reportTime,24*5)
  1334. #解析贷款还款记录指标
  1335. def parseCreditCardMergeAndPayRecordDf(df,payRcdDf):
  1336. if not df.empty and not payRcdDf.empty:
  1337. # 正常
  1338. normalDf = df[(df['账户状态'] != '未激活') & (df['账户状态'] != '销户') & (df['账户状态'] != '呆账')]
  1339. if not normalDf.empty:
  1340. overduePayRcdDf = payRcdDf[payRcdDf['账户编号'].isin(normalDf['账户编号'].values)]
  1341. overduePayRcdDf = utils.replacePayRcdStatus(overduePayRcdDf)
  1342. # 临时保存,不用过滤还款状态为0的
  1343. payRcdMaxOverdueDf = overduePayRcdDf;
  1344. overduePayRcdDf = overduePayRcdDf[overduePayRcdDf['还款状态'] > 0]
  1345. # creditCardAccountInfoDf.loc[creditCardAccountInfoIndex, '当前贷记卡逾期账户数'] = overduePayRcdDf['账户编号'].unique().size
  1346. #从“贷记卡信息”中提取,剔除“账户状态”为未激活、销户、呆账、呆帐后,“当前信用卡逾期账户数”/未销户贷记卡账户数(剔除“账户状态”为未激活、销户、呆账、呆帐后记录条数)
  1347. creditCardAccountInfoDf.loc[creditCardAccountInfoIndex, '当前贷记卡逾期账户数占比'] = round(overduePayRcdDf['账户编号'].unique().size / normalDf.index.size, 2)
  1348. #从“贷记卡信息”中提取,剔除“账户状态”为未激活、销户、呆账、呆帐后,对(当前信用卡逾期账户数)按“开户机构代码”去重统计账户状态为逾期,按按“开户机构代码”去重后的记录条数
  1349. overdueCreditCardDf = normalDf[normalDf['账户编号'].isin(overduePayRcdDf['账户编号'].values)]
  1350. creditCardAccountInfoDf.loc[creditCardAccountInfoIndex, '当前贷记卡逾期机构数'] = overdueCreditCardDf['发卡机构'].unique().size
  1351. creditCardAccountInfoDf.loc[creditCardAccountInfoIndex, '当前贷记卡逾期机构数占比'] = round(creditCardAccountInfoDf.loc[creditCardAccountInfoIndex, '当前贷记卡逾期机构数'] / normalDf['发卡机构'].unique().size, 2)
  1352. creditCardAccountInfoDf.loc[creditCardAccountInfoIndex, '近3月贷记卡最大逾期期数'] = cip.getPayRcdMaxOverdueNum(payRcdMaxOverdueDf, 3);
  1353. creditCardAccountInfoDf.loc[creditCardAccountInfoIndex, '近6月贷记卡最大逾期期数'] = cip.getPayRcdMaxOverdueNum(payRcdMaxOverdueDf, 6);
  1354. creditCardAccountInfoDf.loc[creditCardAccountInfoIndex, '近9月贷记卡最大逾期期数'] = cip.getPayRcdMaxOverdueNum(payRcdMaxOverdueDf, 9);
  1355. creditCardAccountInfoDf.loc[creditCardAccountInfoIndex, '近12月贷记卡最大逾期期数'] = cip.getPayRcdMaxOverdueNum(payRcdMaxOverdueDf, 12);
  1356. creditCardAccountInfoDf.loc[creditCardAccountInfoIndex, '近24月贷记卡最大逾期期数'] = cip.getPayRcdMaxOverdueNum(payRcdMaxOverdueDf, 24);
  1357. reportTime = queryInfo["reportTime"]
  1358. creditCardAccountInfoDf.loc[creditCardAccountInfoIndex, '近24月贷记卡最大逾期距离现在的月数'] = cip.getPayRcdMaxOverdueNumMonth(payRcdMaxOverdueDf,normalDf,reportTime, 24);
  1359. creditCardAccountInfoDf.loc[creditCardAccountInfoIndex, '最近3个月贷记卡最大连续逾期月份数'] = cip.getContinuousOverdueMonth(payRcdMaxOverdueDf,normalDf,3);
  1360. creditCardAccountInfoDf.loc[creditCardAccountInfoIndex, '最近6个月贷记卡最大连续逾期月份数'] = cip.getContinuousOverdueMonth(payRcdMaxOverdueDf,normalDf,6);
  1361. creditCardAccountInfoDf.loc[creditCardAccountInfoIndex, '最近9个月贷记卡最大连续逾期月份数'] = cip.getContinuousOverdueMonth(payRcdMaxOverdueDf,normalDf,9);
  1362. creditCardAccountInfoDf.loc[creditCardAccountInfoIndex, '最近12个月贷记卡最大连续逾期月份数'] = cip.getContinuousOverdueMonth(payRcdMaxOverdueDf,normalDf,12);
  1363. creditCardAccountInfoDf.loc[creditCardAccountInfoIndex, '最近24个月贷记卡最大连续逾期月份数'] = cip.getContinuousOverdueMonth(payRcdMaxOverdueDf,normalDf,24);
  1364. payRcdTimesDf = payRcdDf[payRcdDf['账户编号'].isin(normalDf['账户编号'].values)]
  1365. payRcdTimesDf = payRcdTimesDf.sort_values(by=["账户编号", "还款日期"], ascending=(True, False))
  1366. payRcdTimesDf = payRcdTimesDf.groupby(['账户编号']).head(24)
  1367. payRcdTimesDf = payRcdTimesDf[
  1368. payRcdTimesDf['还款状态'].isin(['G', 'D', 'C', 'N', 'M', '1', '2', '3', '4', '5', '6', '7'])]#从“贷记卡信息”中提取,剔除未激活、销户、呆账、呆帐后,各账户的还款次数统计“24个月(账户)还款状态”包含"G","D","C","N","M"及数字的个数
  1369. creditCardAccountInfoDf.loc[creditCardAccountInfoIndex, '贷记卡24期还款记录次数'] = payRcdTimesDf.index.size
  1370. # 解析被追偿信息汇总
  1371. def parseRecoveryInfoMergeDf(df):
  1372. if not df.empty:
  1373. recoveryMaxPayDf = df[df['债权转移时的还款状态'] !='--']
  1374. recoveryStatusCs = df[df['账户状态'] == '催收']
  1375. if not recoveryMaxPayDf.empty:
  1376. briefInfoDf_recoveryInfoSum.loc[recoveryInfoSumIndex, '债权转移时的最大还款状态'] = np.max(recoveryMaxPayDf['债权转移时的还款状态']);
  1377. briefInfoDf_recoveryInfoSum.loc[recoveryInfoSumIndex, '债权转移时属于催收状态的账户数'] = recoveryStatusCs.index.size;
  1378. briefInfoDf_recoveryInfoSum.loc[recoveryInfoSumIndex, '债权转移时属于催收状态的账户数/被追偿信息总数'] = round(recoveryStatusCs.index.size/df.index.size,2);
  1379. #creditTradeDetailDf_recoveryInfo
  1380. # 被追偿账户总数
  1381. creditTradeDetailDf_recoveryInfo.loc[recoveryInfoIndex,'被追偿账户总数'] = df.index.size;
  1382. creditTradeDetailDf_recoveryInfo.loc[recoveryInfoIndex, '被追偿业务种类'] = df['业务种类'].unique().size;
  1383. creditTradeDetailDf_recoveryInfo.loc[recoveryInfoIndex, '最新一笔被追偿债券接收时间'] = np.max(df['债权接收日期']);
  1384. creditTradeDetailDf_recoveryInfo.loc[recoveryInfoIndex, '总债权金额'] = np.max(df['债权金额']);
  1385. creditTradeDetailDf_recoveryInfo.loc[recoveryInfoIndex, '债权转移时的最大还款状态'] = np.max(recoveryMaxPayDf['债权转移时的还款状态']);
  1386. def main(pdf_path):
  1387. # 解析pdf开始
  1388. with pdfplumber.open(pdf_path) as pdf:
  1389. for p in range(0, len(pdf.pages)):
  1390. page = pdf.pages[p]
  1391. # first_page = pdf.pages[1]
  1392. # if p == 3:
  1393. # print(3)
  1394. tables = page.extract_tables();
  1395. for i in range(0, len(tables)):
  1396. table = tables[i]
  1397. df = pd.DataFrame(table);
  1398. # if p==12:
  1399. # logger.info(p)
  1400. if len(keyList) > 1 and i == 0: # 判断是否被分页了
  1401. if not utils.checkHeader(df, allHeaders):
  1402. key = keyList[-1];
  1403. dfObj = dfMap[key]
  1404. # dfObj["nextDf"]=df;
  1405. # 贷款信息 贷记卡信息 强制执行记录
  1406. if key == "loanDfs" or key == "creditCardDfs" or key == "forceExecRcdDfs" or key == 'recoveryInfoDfs' or key == "housingFundRcdDfs": # 属于列表
  1407. lastDfObj = dfObj["dfs"][-1];
  1408. lastDfObj["isByPage"] = str(p + 1);
  1409. if len(dfObj["dfs"][-1]["df"].columns) == len(df.columns): # 列数相同
  1410. lastDfObj["df"] = pd.concat([lastDfObj["df"], df], axis=0,ignore_index=True); # 去最后一个进行合并
  1411. # print("key-" + key + "-page-" + str(p + 1) + "-" + "###列数相同####-被分页")
  1412. else:
  1413. # print("key-" + key + "-page-" + str(p + 1) + "-" + "列数不同-被分页")
  1414. lastDfObj["df"] = pd.concat([lastDfObj["df"], df], axis=0, ignore_index=True);
  1415. else: # 查询记录明细 为单个列表
  1416. dfObj["isByPage"] = str(p + 1);
  1417. logger.info(key)
  1418. if len(dfObj["df"].columns) == len(df.columns):
  1419. # print("key-" + key + "-page-" + str(p + 1) + "-" + "###列数相同####-被分页")
  1420. dfObj["df"] = pd.concat([dfObj["df"], df], axis=0, ignore_index=True)
  1421. else:
  1422. # print("key-" + key + "-page-" + str(p + 1) + "-" + "列数不同-被分页")
  1423. dfObj["df"] = pd.concat([dfObj["df"], df], axis=0, ignore_index=True)
  1424. # dfObj["nextDf"] = df;
  1425. # 如果列数相等合并df
  1426. continue;
  1427. headerList0 = df.loc[0, :].tolist() # 第0行为表头
  1428. headerList0 = list(filter(None, headerList0))
  1429. headerList1 = []
  1430. if df.index.size>1:
  1431. headerList1 = df.loc[1, :].tolist() # 第1行为表头
  1432. headerList1 = list(filter(None, headerList1))
  1433. if headerList1 == queryInfoDf_header: # 被查询信息 第二行为数据
  1434. queryInfoDf = df;
  1435. dfKey = "queryInfoDf"
  1436. dfMap[dfKey]["df"] = df;
  1437. keyList.append(dfKey);
  1438. elif headerList0 == identity_header: # 身份信息
  1439. identityDf = df[:2] # 截取前2行
  1440. addressDf = df.loc[2:4,:] # 截取3到4行的第一和6
  1441. addressDf = addressDf.reset_index(drop=True)
  1442. mobileDf = utils.replaceDateColIdx(df[5:df.index.size], 5)
  1443. identityDf = pd.concat([identityDf, addressDf], axis=1, ignore_index=True) # 横向合并
  1444. dfKey = "identityDf"
  1445. dfMap[dfKey]["df"] = identityDf;
  1446. keyList.append(dfKey);
  1447. # 组装电话号码df
  1448. dfMap[dfKey]["mobileDf"] = mobileDf
  1449. elif headerList0 == mateDf_header: # 配偶信息
  1450. mateDf = df;
  1451. dfKey = "mateDf"
  1452. dfMap[dfKey]["df"] = df;
  1453. keyList.append(dfKey);
  1454. elif headerList0 == liveInfoDf_header: # 居住信息
  1455. mateDf = df;
  1456. dfKey = "liveInfoDf"
  1457. dfMap[dfKey]["df"] = df;
  1458. keyList.append(dfKey);
  1459. elif headerList0 == occupationInfo_header: # 职业信息 可能存在分页
  1460. occupationDf = df;
  1461. dfKey = "occupationDf"
  1462. dfMap[dfKey]["df"] = df;
  1463. keyList.append(dfKey);
  1464. # elif headerList0 == queryInfoBrief_header0 and headerList1 == queryInfoBrief_header1: # 查询信息概要 第二行为数据
  1465. # queryInfoBriefDf = df;
  1466. # dfKey = "queryInfoBriefDf"
  1467. # dfMap[dfKey]["df"] = df;
  1468. # keyList.append(dfKey);
  1469. elif headerList0 == loanTradeInfo_header: # 信贷交易信息
  1470. loanTradeInfoDf = df;
  1471. dfKey = "loanTradeInfoDf";
  1472. dfMap[dfKey]["df"] = df;
  1473. keyList.append(dfKey);
  1474. elif headerList1 == recoveryInfoSumDf_header: # 被追偿信息汇总
  1475. recoveryInfoSumDf = df;
  1476. dfKey = "recoveryInfoSumDf";
  1477. dfMap[dfKey]["df"] = df;
  1478. keyList.append(dfKey);
  1479. elif headerList1 == badDebtsInfoSumDf_header: # 呆账信息
  1480. badDebtsInfoSumDf = df;
  1481. dfKey = "badDebtsInfoSumDf";
  1482. dfMap[dfKey]["df"] = df;
  1483. keyList.append(dfKey);
  1484. elif headerList1 == overdueInfoSumDf_header: # 逾期透资信息汇总
  1485. overdueInfoSumDf = df;
  1486. dfKey = "overdueInfoSumDf";
  1487. dfMap[dfKey]["df"] = df;
  1488. keyList.append(dfKey);
  1489. elif headerList0 == loanAccountInfoSumDf_header0 and headerList1 == loanAccountInfoSumDf_header1: # 非循环贷账户信息汇总
  1490. loanAccountInfoSumDf = df;
  1491. dfKey = "loanAccountInfoSumDf";
  1492. dfMap[dfKey]["df"] = df;
  1493. keyList.append(dfKey);
  1494. elif headerList0 == creditCardInfoSumDf_header0 and headerList1 == creditCardInfoSumDf_header1: # 贷记卡信息汇总
  1495. creditCardInfoSumDf = df;
  1496. dfKey = "creditCardInfoSumDf";
  1497. dfMap[dfKey]["df"] = df;
  1498. keyList.append(dfKey);
  1499. elif headerList0 == creditCardInfoSumDfZ_header0 and headerList1 == creditCardInfoSumDfZ_header1: # 准贷记卡信息汇总 目前没有数据
  1500. dfKey = "creditCardInfoSumDfZ";
  1501. dfMap[dfKey]["df"] = df;
  1502. keyList.append(dfKey);
  1503. elif headerList0 == repaymentSumDf_header0:#相关还款责任汇总
  1504. dfKey = "repaymentSumDf";
  1505. dfMap[dfKey]["df"] = df;
  1506. keyList.append(dfKey);
  1507. elif headerList0 == publicInfoBriefDf_header0: #公共信息概要
  1508. dfKey = "publicInfoBriefDf";
  1509. dfMap[dfKey]["df"] = df;
  1510. keyList.append(dfKey);
  1511. elif headerList0 == queryRecordSumDf_header0:#查询记录汇总
  1512. dfKey = "queryRecordSumDf";
  1513. dfMap[dfKey]["df"] = df;
  1514. keyList.append(dfKey);
  1515. elif headerList0 == loan_header: # 贷款账户 包括循环贷,非循环贷 循环额度下分账户
  1516. dfKey = "loanDfs";
  1517. dfMap[dfKey]["dfs"].append({"df": df});
  1518. keyList.append(dfKey);
  1519. elif headerList0 == creditCard_header: # 贷记卡账户
  1520. dfKey = "creditCardDfs";
  1521. dfMap[dfKey]["dfs"].append({"df": df});
  1522. keyList.append(dfKey);
  1523. elif headerList0 == creditCardZ_header: # 准贷记卡账户 还不能和贷记卡合并
  1524. dfKey = "creditCardDfsZ";
  1525. dfMap[dfKey]["dfs"].append({"df": df});
  1526. keyList.append(dfKey);
  1527. elif headerList0 == queryRecordDetailDf_header: # 查询记录明细
  1528. dfKey = "queryRecordDetailDf";
  1529. dfMap[dfKey]["df"] = df;
  1530. keyList.append(dfKey);
  1531. elif headerList0 == housingFundRcdDfs_header: # 查询记录明细
  1532. dfKey = "housingFundRcdDfs";
  1533. dfMap[dfKey]["dfs"].append({"df": df});
  1534. keyList.append(dfKey);
  1535. elif headerList0 == forceExecRcdDfs_header: # 强制执行记录
  1536. dfKey = "forceExecRcdDfs";
  1537. dfMap[dfKey]["dfs"].append({"df": df});
  1538. keyList.append(dfKey);
  1539. elif headerList0 == recoveryInfoDfs_header: # 被追偿信息
  1540. dfKey = "recoveryInfoDfs";
  1541. dfMap[dfKey]["dfs"].append({"df": df});
  1542. keyList.append(dfKey);
  1543. # 设置分页
  1544. dfMap[dfKey]["page"] = p + 1;
  1545. logger.info("组装pdf数据完成")
  1546. logger.info("解析基础pdf数据开始")
  1547. # 打印结果解析并构建指标
  1548. for key in dfMap:
  1549. tempDfObjx = dfMap[key];
  1550. if tempDfObjx.__contains__("page"):
  1551. logger.info(key + "-page-" + str(tempDfObjx["page"]))
  1552. if tempDfObjx.__contains__("dfs"):
  1553. if key == "loanDfs": # 贷款账户
  1554. for idx in range(0, len(tempDfObjx["dfs"])):
  1555. tempDfObj = tempDfObjx["dfs"][idx];
  1556. loanAccountDfs.append(dfParser.mergeLoanDf(tempDfObj, idx,queryInfo['reportTime']))
  1557. elif key == "creditCardDfs": # 贷记卡账户合并
  1558. for idx in range(0, len(tempDfObjx["dfs"])):
  1559. tempDfObj = tempDfObjx["dfs"][idx];
  1560. tempCreditCardDf = dfParser.mergeCreditCardDf(tempDfObj, idx,queryInfo['reportTime']);
  1561. if tempCreditCardDf!=None:
  1562. creditCardAccountDfs.append(tempCreditCardDf)
  1563. elif key == "creditCardDfsZ": # 贷记卡账户合并
  1564. for idx in range(0, len(tempDfObjx["dfs"])):
  1565. tempDfObj = tempDfObjx["dfs"][idx];
  1566. tempCreditCardDfZ = dfParser.mergeCreditCardDfZ(tempDfObj, idx,queryInfo['reportTime'])
  1567. if tempCreditCardDfZ!=None:
  1568. creditCardAccountDfsZ.append(tempCreditCardDfZ)
  1569. elif key == "recoveryInfoDfs": # 贷记卡账户合并
  1570. for idx in range(0, len(tempDfObjx["dfs"])):
  1571. tempDfObj = tempDfObjx["dfs"][idx];
  1572. recoveryInfoAccountDfs.append(dfParser.mergeRecoveryInfoDf(tempDfObj, idx, queryInfo['reportTime']))
  1573. elif key == "housingFundRcdDfs": # 贷记卡账户合并
  1574. for idx in range(0, len(tempDfObjx["dfs"])):
  1575. tempDfObj = tempDfObjx["dfs"][idx];
  1576. housingFundRcdAccountDfs.append(dfParser.mergeHousingFundRcdDf(tempDfObj, idx, queryInfo['reportTime']))
  1577. else: # 其他
  1578. for tempDfObj in (tempDfObjx["dfs"]):
  1579. if tempDfObj.__contains__("isByPage"):
  1580. logger.info(key + "============其他被分页页数============" + str(tempDfObj["isByPage"]))
  1581. # logger.info(tempDfObj["df"].values)
  1582. else: # 单笔
  1583. tempDfObj = tempDfObjx;
  1584. if tempDfObj.__contains__("isByPage"):
  1585. logger.info(key + "============被分页页数================" + str(tempDfObj["isByPage"]))
  1586. # logger.info(tempDfObj["df"].values)
  1587. if key == "queryInfoDf": # 解析被查询信息
  1588. parseQueryInfo(tempDfObj);
  1589. # print("\033[1;31m +查询信息+ \033[0m")
  1590. # print(queryInfo)
  1591. elif key == "identityDf": # 身份信息
  1592. parseIdentity(tempDfObj)
  1593. # print("\033[1;31m +身份信息+ \033[0m")
  1594. # print(identity)
  1595. elif key == "mateDf": # 配偶信息
  1596. parseMate(tempDfObj)
  1597. # print("\033[1;31m +配偶信息+ \033[0m")
  1598. # print(mate)
  1599. elif key == "liveInfoDf": # 居住信息
  1600. parseLiveInfo(tempDfObj)
  1601. # print("\033[1;31m +居住信息+ \033[0m")
  1602. elif key == "occupationDf": # 居住信息
  1603. parseOccupationInfoDf(tempDfObj)
  1604. elif key == "loanTradeInfoDf": # 信贷交易信息提示
  1605. parseLoanTradeInfo(tempDfObj);
  1606. # print("\033[1;31m +信贷交易信息提示+ \033[0m")
  1607. # print(loanTradeInfo)
  1608. elif key == "badDebtsInfoSumDf": # 呆账信息汇总
  1609. parseBadDebtsInfoSumDf(tempDfObj)
  1610. # print("\033[1;31m +呆账信息汇总+ \033[0m")
  1611. # print(overdueBrief)
  1612. elif key == "recoveryInfoSumDf": # 被追偿信息汇总-资产处置和垫款
  1613. parseRecoveryInfoSum(tempDfObj)
  1614. # print("\033[1;31m +资产处置和垫款+ \033[0m")
  1615. # print(overdueBrief)
  1616. elif key == "overdueInfoSumDf": # 逾期(透支)信息汇总
  1617. parseOverdueInfoSum(tempDfObj)
  1618. # print("\033[1;31m +逾期(透支)信息汇总+ \033[0m")
  1619. # print(overdueInfo)
  1620. elif key == "loanAccountInfoSumDf": # 非循环贷账户信息汇总 TODO
  1621. parseLoanAccountInfoSum(tempDfObj)
  1622. elif key == "cycleCreditAccountInfoSumDf":#循环额度
  1623. parseCycleCreditAccountInfoSum(tempDfObj)
  1624. elif key == "cycleLoanAccountInfoSumDf":#循环贷
  1625. parseCyleLoanAccountInfoSum(tempDfObj)
  1626. elif key == "creditCardInfoSumDf":#贷记卡
  1627. parseCreditCardInfoSum(tempDfObj)
  1628. elif key == "creditCardInfoSumDfZ": # 准贷记卡
  1629. parseCreditCardInfoSumZ(tempDfObj)
  1630. elif key == "repaymentSumDf": # 相关还款责任
  1631. parseRepaymentSum(tempDfObj)
  1632. elif key == "publicInfoBriefDf":
  1633. parsePublicInfoBrief(tempDfObj);
  1634. elif key == "queryRecordSumDf":
  1635. parseQueryRecordSum(tempDfObj);
  1636. elif key == "queryRecordDetailDf": # 查询记录明细
  1637. parseQueryInfoDetail(tempDfObj)#
  1638. logger.info("解析基础pdf数据完成")
  1639. result = "{"
  1640. # 基本信息
  1641. # result+=("\033[1;34m +身份信息+ \033[0m")+"\n"
  1642. result+=utils.toJson(identityInfoDf)+","
  1643. result += utils.toJson(mateInfoDf) + ","
  1644. result += utils.toJson(liveInfoDf) + ","
  1645. result += utils.toJson(occupationInfoDf) + ","
  1646. # result+=("\033[1;34m +概要信息+ \033[0m")+","
  1647. # result+=("\033[1;34m +信贷交易信息提示+ \033[0m")+","
  1648. result+=utils.toJson(briefInfoDf_loanTradeInfo)+","
  1649. # result+=("\033[1;34m +被追偿信息汇总及呆账信息汇总+ \033[0m")+","
  1650. result+="briefInfoDf_recoveryInfoSum"+"," #占位符
  1651. result += utils.toJson(briefInfoDf_badDebtsInfoSum) + ","
  1652. # result+=("\033[1;34m +逾期(透支)信息汇总+ \033[0m")+","
  1653. #此信息先占位
  1654. result+="briefInfoDf_overdueInfoSum"+","
  1655. # result+=("\033[1;34m +信贷交易授信及负债信息概要+ \033[0m")+","
  1656. result+=utils.toJson(briefInfoDf_loanTradeCreditInfo)+","
  1657. #公共信息
  1658. result += utils.toJson(publicInfoBriefDf) + ","
  1659. #查询记录汇总
  1660. result += utils.toJson(queryRecordSumDf) + ","
  1661. # 单独输出贷款df
  1662. # logger.info("\033[1;34m +贷款信息Dataframe+ \033[0m")
  1663. # logger.info(dfParser.dfHeaderLoan)
  1664. logger.info("解析贷款数据开始")
  1665. loanMergeDf = pd.DataFrame(columns=dfParser.dfHeaderLoan)
  1666. loanPayRecordMergeDf = pd.DataFrame(columns=dfParser.dfHeaderLoanPayRecord)
  1667. loanSpecialTradeMergeDf = pd.DataFrame(columns=dfParser.dfHeaderLoanSpecialTrade)#特殊交易
  1668. # 输出数据
  1669. for loanDfObj in loanAccountDfs:
  1670. loanMergeDf = pd.concat([loanMergeDf, loanDfObj["loanDf"]], axis=0, ignore_index=True);
  1671. loanPayRecordMergeDf = pd.concat([loanPayRecordMergeDf, loanDfObj["loanPayRecordDf"]], axis=0,ignore_index=True);
  1672. loanSpecialTradeMergeDf = pd.concat([loanSpecialTradeMergeDf, loanDfObj["specialTradeDf"]], axis=0, ignore_index=True);
  1673. # logger.info(loanMergeDf.values)
  1674. # logger.info("\033[1;34m +贷款信息还款记录Dataframe+ \033[0m")
  1675. # logger.info(dfParser.dfHeaderLoanPayRecord)
  1676. # logger.info(loanPayRecordMergeDf.values)
  1677. #
  1678. #==============================信贷交易明细 ===============================
  1679. #被追偿信息
  1680. # 被追偿信息合并df
  1681. recoveryInfoMergeDf = pd.DataFrame(columns=dfParser.dfHeaderRecoveryInfo)
  1682. for recoveryInfoDfObj in recoveryInfoAccountDfs:
  1683. recoveryInfoMergeDf = pd.concat([recoveryInfoMergeDf, recoveryInfoDfObj["recoveryInfoDf"]], axis=0,
  1684. ignore_index=True);
  1685. parseRecoveryInfoMergeDf(recoveryInfoMergeDf);
  1686. #被追偿信息
  1687. result = result.replace("briefInfoDf_recoveryInfoSum", utils.toJson(briefInfoDf_recoveryInfoSum))#替换汇总中的指标
  1688. result += utils.toJson(creditTradeDetailDf_recoveryInfo) + "," #设置占位符,由于存在概要的指标在明细中计算
  1689. #特殊交易
  1690. parseSpecialTrade(loanSpecialTradeMergeDf)
  1691. result += utils.toJson(creditTradeDetailHeader_specialTrade) + ","
  1692. # 信贷交易明细-解析非循环贷账户
  1693. parseLoanAccountInfo(loanMergeDf);
  1694. result += utils.toJson(creditTradeDetailDf_loanAccountInfo) + ","
  1695. #循环额度分账户
  1696. parseCycleCreditAccountInfo(loanMergeDf);
  1697. result += utils.toJson(creditTradeDetailDf_cycleCreditAccountInfo) + ","
  1698. #循环贷
  1699. parseCycleLoanAccountInfo(loanMergeDf);
  1700. result += utils.toJson(creditTradeDetailDf_cycleLoanAccountInfo) + ","
  1701. # 解析贷款账户指标
  1702. parseLoanMergeDf(loanMergeDf);
  1703. # 解析还款记录相关指标
  1704. parseLoanMergeAndPayRecordDf(loanMergeDf, loanPayRecordMergeDf);
  1705. # logger.info(loanAccountInfo)
  1706. # logger.info(consts.loanAccountInfoHeader)
  1707. # logger.info(loanAccountInfoDf.values)
  1708. # result+=("\033[1;34m +贷款账户信息+ \033[0m")+","
  1709. result+=utils.toJson(loanAccountInfoDf)+","
  1710. logger.info("解析贷款数据完成")
  1711. logger.info("解析贷记卡数据开始")
  1712. #贷记卡合并df
  1713. creditCardMergeDf = pd.DataFrame(columns=dfParser.dfHeaderCreditCard)
  1714. creditCardPayRecordMergeDf = pd.DataFrame(columns=dfParser.dfHeaderCreditCardPayRecord)
  1715. # logger.info("\033[1;34m +贷记卡信息Dataframe+ \033[0m")
  1716. # logger.info(dfParser.dfHeaderCreditCard)
  1717. # 输出数据
  1718. for creditCardDfObj in creditCardAccountDfs:
  1719. creditCardMergeDf = pd.concat([creditCardMergeDf, creditCardDfObj["creditCardDf"]], axis=0, ignore_index=True);
  1720. creditCardPayRecordMergeDf = pd.concat([creditCardPayRecordMergeDf, creditCardDfObj["creditCardPayRecordDf"]], axis=0,ignore_index=True);
  1721. # logger.info(creditCardMergeDf.values)
  1722. # 解析贷记卡账户指标
  1723. parseCreditCardMergeDf(creditCardMergeDf);
  1724. parseCreditCardMergeAndPayRecordDf(creditCardMergeDf,creditCardPayRecordMergeDf)
  1725. #准贷记卡合并df
  1726. creditCardMergeDfZ = pd.DataFrame(columns=dfParser.dfHeaderCreditCardZ)
  1727. creditCardPayRecordMergeDfZ = pd.DataFrame(columns=dfParser.dfHeaderCreditCardPayRecordZ)
  1728. for creditCardDfObj in creditCardAccountDfsZ:
  1729. creditCardMergeDfZ = pd.concat([creditCardMergeDfZ, creditCardDfObj["creditCardDfZ"]], axis=0, ignore_index=True);
  1730. creditCardPayRecordMergeDfZ = pd.concat([creditCardPayRecordMergeDfZ, creditCardDfObj["creditCardPayRecordDfZ"]], axis=0,ignore_index=True);
  1731. #解析准贷记卡相关指标
  1732. parseCreditCardMergeDfZ(creditCardMergeDfZ,creditCardPayRecordMergeDfZ);
  1733. logger.info("解析贷记卡数据完成")
  1734. #加工使用率指标
  1735. # result+=("\033[1;34m +贷记卡账户信息+ \033[0m")+","
  1736. result+=utils.toJson(creditCardAccountInfoDf)+","
  1737. result += utils.toJson(creditCardAccountInfoDfZ) + ","
  1738. #使用率
  1739. parseUseRate()
  1740. result += utils.toJson(useRateDf) + ","
  1741. #开户数
  1742. parseOpenAccount(loanMergeDf, creditCardMergeDf, creditCardMergeDfZ,recoveryInfoMergeDf,loanPayRecordMergeDf,creditCardPayRecordMergeDf,creditCardPayRecordMergeDfZ)
  1743. result += utils.toJson(openAccountDf) + ","
  1744. #24期还款状态
  1745. parsePayRcdStatus(loanMergeDf, creditCardMergeDf, creditCardMergeDfZ,loanPayRecordMergeDf,creditCardPayRecordMergeDf,creditCardPayRecordMergeDfZ)
  1746. result += utils.toJson(payRcdStatusDf) + ","
  1747. #由于逾期汇总的指标再还款状态之后需要替换占位 TODO
  1748. result = result.replace("briefInfoDf_overdueInfoSum",utils.toJson(briefInfoDf_overdueInfoSum))
  1749. #公积金
  1750. # 被追偿信息合并df
  1751. housingFundRcdMergeDf = pd.DataFrame(columns=dfParser.dfHeaderHousingFundRcd)
  1752. for housingFundRcdDfObj in housingFundRcdAccountDfs:
  1753. housingFundRcdMergeDf = pd.concat([housingFundRcdMergeDf, housingFundRcdDfObj["housingFundRcdDf"]], axis=0,ignore_index=True);
  1754. parseHousingFundRcd(housingFundRcdMergeDf);
  1755. result += utils.toJson(housingFundRcdDf) + ","
  1756. # result+=("\033[1;34m +查询记录明细+ \033[0m")+","
  1757. result+=utils.toJson(queryRecordDetailDf)+""
  1758. result +="}"
  1759. return result;
  1760. def uploadReportResult(basePath,pdf_path):
  1761. # ===================================
  1762. logger.info("准备上传文件")
  1763. uploadApiUrl = config.get("baseconf", "uploadApiUrl");
  1764. uploadApiUrl = uploadApiUrl + "?access_token=" + dbController.getToken()
  1765. files = {'file': open(outPath, 'rb')}
  1766. businessNum = dbController.getBussinessNum(queryInfo["queryInfoCardId"]); # 根据身份证获取业务编号
  1767. logger.info("businessNum:"+businessNum)
  1768. logger.info("queryInfoCardId:" + queryInfo["queryInfoCardId"])
  1769. data = {'docType': "23", 'businessNum': businessNum}
  1770. response = requests.post(uploadApiUrl, files=files, data=data)
  1771. text = response.text
  1772. p = PrpCrypt(config.get("baseconf", "AESKey"))
  1773. # logger.info("token:"+token)
  1774. # logger.info(url)
  1775. # logger.info(result.text)
  1776. resultText = p.decrypt(text)
  1777. logger.info("upload_result:" + resultText)
  1778. try:
  1779. descPdfPath = basePath + "execed/" + os.path.basename(pdf_path)
  1780. if not os.path.exists(basePath+"execed/"):
  1781. os.mkdir(basePath+"execed/")
  1782. shutil.move(pdf_path, descPdfPath)
  1783. # shutil.move(pdf_path.replace("pdf","txt"), descPdfPath.replace("pdf","txt"))
  1784. except:
  1785. info = sys.exc_info()
  1786. logger.error(info[0])
  1787. logger.error(info[1])
  1788. # logging.log(logging.ERROR, info[2])
  1789. logger.error(traceback.extract_tb(info[2], 1))
  1790. def updateParseInd(file_name):
  1791. # 检查是否存在已执行
  1792. parseInd = "1"
  1793. try:
  1794. if file_name != "":
  1795. arCert = file_name[0:-4].split("_")
  1796. if len(arCert) == 2:
  1797. cert_id = arCert[1]
  1798. parseIndTmp = dbController.getParseInd(cert_id)
  1799. if parseIndTmp =="1":
  1800. return True
  1801. dbController.updateParseInd(cert_id, parseInd)
  1802. except:
  1803. logger.error("update parse ind error")
  1804. return False
  1805. # grouped.to_csv(r'C:\Users\Mortal\Desktop\ex.csv',index=False, encoding='utf_8_sig')
  1806. if __name__ == '__main__':
  1807. file_name = ""
  1808. # basePath = "D:/mydocument/myproject/git/busscredit/20200430_report/";
  1809. basePath = "D:/mydocument/myprojects/creditreport/parse/"
  1810. # file_name = "周颖500108199002111229.pdf"#准贷记卡已销户 呆账
  1811. # file_name = "王思13052819911012122X.pdf"#公积金
  1812. # file_name = "杨夏龙440902198410014270.pdf"#转出
  1813. # file_name = "翟彦超230125199004174216.pdf"#准贷记卡 呆账
  1814. # file_name = "蔡月辉330326198502116146.pdf" # 配偶
  1815. # file_name = "周芳芳342501198706111782.pdf" #被追偿信息
  1816. # file_name = "付春雁533001198507220344.pdf" # 公积金记录
  1817. # pdf_path = basePath + "陈洁350122199005027726.pdf" # 相关还款责任
  1818. file_name = "曹红23012719900301108X.pdf" # 相关还款责任
  1819. pdf_path = basePath + file_name
  1820. if len(sys.argv)>1:
  1821. basePath = sys.argv[1]
  1822. pdf_path = basePath + sys.argv[2]
  1823. file_name = sys.argv[2]
  1824. # print(sys.argv)
  1825. isBat = False#批量的有问题
  1826. isPlt = config.get("baseconf", "isPlt");
  1827. if isBat:#批量生成数据不对
  1828. for file in os.listdir(basePath):
  1829. if file.endswith("pdf"):
  1830. start = timeit.default_timer();
  1831. pdf_path = basePath+file;
  1832. outPath = pdf_path.replace("pdf",'txt')
  1833. if os.path.exists(outPath):
  1834. continue;
  1835. logger.info(file + "解析开始...")
  1836. try:
  1837. result = main(pdf_path)
  1838. except:
  1839. info = sys.exc_info()
  1840. logger.error(info[0])
  1841. logger.error( info[1])
  1842. # logging.log(logging.ERROR, info[2])
  1843. logger.error(traceback.extract_tb(info[2], 1))
  1844. # print(result)
  1845. #输出到文件
  1846. sys.stdout = open(outPath, mode='w', encoding='utf-8')
  1847. print(result.replace("\033[1;34m","").replace("\033[0m",""))
  1848. logger.info(file+"解析完成")
  1849. gc.collect()
  1850. s = timeit.default_timer() - start;
  1851. logger.info(str(s) + " 秒")
  1852. else:
  1853. if pdf_path.endswith("pdf"):
  1854. start = timeit.default_timer();
  1855. outPath = pdf_path.replace("pdf", 'txt')
  1856. result = ""
  1857. if isPlt == "1":#生产模式
  1858. if not os.path.exists(outPath):#不存在才生成
  1859. isExec = updateParseInd(file_name)
  1860. if not isExec:#没有在执行
  1861. try:
  1862. logger.info(pdf_path + "解析开始...")
  1863. result = main(pdf_path)
  1864. sys.stdout = open(outPath, mode='w', encoding='utf-8')
  1865. print(result.replace("\033[1;34m", "").replace("\033[0m", ""))
  1866. logger.info(pdf_path + "解析完成")
  1867. s = timeit.default_timer() - start;
  1868. logger.info(str(s) + " 秒")
  1869. uploadReportResult(basePath,pdf_path);
  1870. except:
  1871. info = sys.exc_info()
  1872. logger.error(pdf_path+"#"+"解析失败")
  1873. logger.error(info[0])
  1874. logger.error(info[1])
  1875. logger.error(traceback.extract_tb(info[2]))
  1876. else:
  1877. isExec = updateParseInd(file_name)
  1878. if not isExec: # 没有在执行
  1879. result = main(pdf_path)
  1880. sys.stdout = open(outPath, mode='w', encoding='utf-8')
  1881. print(result.replace("\033[1;34m", "").replace("\033[0m", ""))
  1882. logger.info(pdf_path + "解析完成")
  1883. s = timeit.default_timer() - start;
  1884. logger.info(str(s) + " 秒")
  1885. uploadReportResult(basePath,pdf_path);