parseCreditPdf.py0520 146 KB

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