{"id":9028,"date":"2023-10-27T15:10:28","date_gmt":"2023-10-27T07:10:28","guid":{"rendered":"\/?p=9028"},"modified":"2023-10-27T15:10:28","modified_gmt":"2023-10-27T07:10:28","slug":"pandas%e8%a7%a3%e6%9e%90excel%e6%96%87%e4%bb%b6","status":"publish","type":"post","link":"\/?p=9028","title":{"rendered":"pandas\u89e3\u6790excel\u6587\u4ef6"},"content":{"rendered":"<pre><code class=\"language-python\"># -*- coding: UTF-8 -*-\n&quot;&quot;&quot;=========================================================\n@Project -&gt; File: ReportAnalysis -&gt; AnalysisMain\n@IDE: PyCharm\n@author: lxc\n@date: 2023-10-24 \u4e0b\u5348 3:02\n@Desc:\n1-\u529f\u80fd\u63cf\u8ff0\uff1a\n\u4e2d\u8f66\u9879\u76ee\u652f\u6301\n\u5c06excel\u6587\u4ef6\u8def\u5f84\u6dfb\u52a0\u5230\u4e00\u4e2a\u5217\u8868\u4e2d\uff0c\u518d\u904d\u5386\u8be5\u5217\u8868\uff0c\u4f9d\u6b21\u5904\u7406\u8868\u683c\u5185\u5bb9\n2-\u5b9e\u73b0\u6b65\u9aa4\n    1- \u8bfb\u53d6\u6587\u4ef6\u6839\u8def\u5f84\uff0c\u76ee\u7684\u662f\u6dfb\u52a0\u6587\u4ef6\u8def\u5f84\u5217\u8868\uff1a\n        \u5982\u679c\u78b0\u5230\u538b\u7f29\u5305\uff0c\u5219\u89e3\u538b\u8be5\u6587\u4ef6\uff0c\u518d\u5904\u7406\u89e3\u538b\u540e\u7684\u8def\u5f84\uff0c\u9012\u5f52\u8be5\u65b9\u6cd5\uff1b\n        \u5982\u679c\u78b0\u5230excel\u6587\u4ef6(\u4e0d\u8bba\u662fxls\u8fd8\u662fxlsx)\uff0c\u5219\u6dfb\u52a0\u8fdb\u6587\u4ef6\u8def\u5f84\u5217\u8868\uff1b\n        \u5982\u679c\u78b0\u5230\u8def\u5f84\uff0c\u5219\u518d\u9012\u5f52\u8be5\u65b9\u6cd5\n        \u8fd9\u6837\u4e00\u6765\u4fbf\u5f97\u5230\u4e86\u8be5\u8def\u5f84\u4e0b\u7684\u6240\u6709excel\u6587\u4ef6\n    2- \u5904\u7406excel\u6587\u4ef6\uff0c\u6309\u6307\u5b9a\u9700\u6c42\u5c06\u8868\u683c\u5185\u5bb9\u63d0\u53d6\u6210\u9700\u6c42\u5b57\u6bb5\u5bf9\u5e94\u7684\u5b57\u5178\n    3- \u5c06item\u5143\u6570\u636e\u5165\u5e93\n3-\u5305\u8bf4\u660e\uff1a\n    1- \u6d4b\u8bd5\u6570\u636e\u5e93\u4f7f\u7528\u4e86peewee\u8fde\u63a5sqlite\n    2- \u4f7f\u7528\u4e86pandas\u5904\u7406excel\u8868\u683c\uff0c\u8bfb\u53d6xls\u548cxlsx\u5206\u522b\u4f9d\u9760openpyxl\u3001xlrd\u5f15\u64ce\n&quot;&quot;&quot;\nimport json\nimport re\nimport os\nimport zipfile\nimport pandas as pd\nimport math\nimport logging\nimport datetime\n# from utils.model import ZhongChe\n\nlogger = logging.getLogger()\n\ndef industry_mapping(company_name):\n    &quot;&quot;&quot;\n    \u516c\u53f8-\u4ea7\u4e1a\u5173\u7cfb\n    :return: industry_name\n    &quot;&quot;&quot;\n    mapping = {\n        &quot;\u4e2d\u8f66\u5c71\u4e1c\u673a\u8f66\u8f66\u8f86\u6709\u9650\u516c\u53f8\uff08\u5408\u5e76\uff09&quot;: &quot;\u8f68\u9053\u4ea4\u901a\u88c5\u5907\u4ea7\u4e1a\uff08\u8d27\u8f66\uff09&quot;,\n        &quot;\u4e2d\u8f66\u5c71\u4e1c\u673a\u8f66\u8f66\u8f86\u6709\u9650\u516c\u53f8\uff08\u5dee\u989d\uff09&quot;: &quot;\u8f68\u9053\u4ea4\u901a\u88c5\u5907\u4ea7\u4e1a\uff08\u8d27\u8f66\uff09&quot;,\n        &quot;\u4e2d\u8f66\u5c71\u4e1c\u673a\u8f66\u8f66\u8f86\u6709\u9650\u516c\u53f8\uff08\u4e2a\u4f53\uff09&quot;: &quot;\u8f68\u9053\u4ea4\u901a\u88c5\u5907\u4ea7\u4e1a\uff08\u8d27\u8f66\uff09&quot;,\n        &quot;\u4e2d\u8f66\u5c71\u4e1c\u673a\u8f66\u8f66\u8f86\u6709\u9650\u516c\u53f8&quot;: &quot;\u8f68\u9053\u4ea4\u901a\u88c5\u5907\u4ea7\u4e1a\uff08\u8d27\u8f66\uff09&quot;,\n        &quot;\u4e2d\u8f66\u5c71\u4e1c\u98ce\u7535\u6709\u9650\u516c\u53f8\uff08\u5408\u5e76\uff09&quot;: &quot;\u98ce\u7535\u4ea7\u4e1a&quot;,\n        &quot;\u4e2d\u8f66\u5c71\u4e1c\u98ce\u7535\u6709\u9650\u516c\u53f8\uff08\u5dee\u989d\uff09&quot;: &quot;\u98ce\u7535\u4ea7\u4e1a&quot;,\n        &quot;\u4e2d\u8f66\u5c71\u4e1c\u98ce\u7535\u6709\u9650\u516c\u53f8\uff08\u4e2a\u4f53\uff09&quot;: &quot;\u98ce\u7535\u4ea7\u4e1a&quot;,\n        &quot;\u4e2d\u8f66\u5c71\u4e1c\u98ce\u7535\u6709\u9650\u516c\u53f8&quot;: &quot;\u98ce\u7535\u4ea7\u4e1a&quot;,\n        &quot;\u5409\u6797\u4e2d\u8f66\u98ce\u7535\u88c5\u5907\u6709\u9650\u516c\u53f8&quot;: &quot;\u98ce\u7535\u4ea7\u4e1a&quot;,\n        &quot;\u5c71\u4e1c\u4e2d\u8f66\u540c\u529b\u94a2\u6784\u6709\u9650\u516c\u53f8&quot;: &quot;\u98ce\u7535\u4ea7\u4e1a&quot;,\n        &quot;\u6cb3\u5317\u4e2d\u8f66\u98ce\u7535\u88c5\u5907\u6709\u9650\u516c\u53f8&quot;: &quot;\u98ce\u7535\u4ea7\u4e1a&quot;,\n        &quot;\u5c71\u4e1c\u4e2d\u8f66\u540c\u529b\u8fbe\u667a\u80fd\u88c5\u5907\u6709\u9650\u516c\u53f8&quot;: &quot;\u667a\u80fd\u88c5\u5907\u4ea7\u4e1a&quot;,\n        &quot;\u6c5f\u82cf\u4e2d\u8f66\u534e\u817e\u73af\u4fdd\u79d1\u6280\u6709\u9650\u516c\u53f8&quot;: &quot;\u73af\u4fdd\u4ea7\u4e1a&quot;,\n        &quot;\u5e38\u719f\u4e2d\u8f66\u6c34\u52a1\u6709\u9650\u516c\u53f8&quot;: &quot;\u73af\u4fdd\u4ea7\u4e1a&quot;,\n        &quot;\u4e39\u68f1\u4e2d\u8f66\u6c34\u52a1\u6709\u9650\u516c\u53f8&quot;: &quot;\u73af\u4fdd\u4ea7\u4e1a&quot;,\n        &quot;\u5e38\u719f\u4e2d\u8f66\u6751\u9547\u6c34\u52a1\u6709\u9650\u516c\u53f8&quot;: &quot;\u73af\u4fdd\u4ea7\u4e1a&quot;,\n        &quot;\u5e38\u719f\u4e2d\u8f66\u73af\u4fdd\u6c34\u52a1\u6709\u9650\u516c\u53f8&quot;: &quot;\u73af\u4fdd\u4ea7\u4e1a&quot;,\n        &quot;\u4e2d\u8f66\u98ce\u7535\uff08\u9521\u6797\u90ed\u52d2\uff09\u6709\u9650\u516c\u53f8&quot;: &quot;\u98ce\u7535\u4ea7\u4e1a&quot;\n    }\n    return mapping.get(company_name, &#039;&#039;)\n\ndef processing_bracket(string):\n    &quot;&quot;&quot;\n    \u5904\u7406\u5b57\u7b26\u4e32\u4e2d\u7684\u62ec\u53f7\u5185\u5bb9\uff0c\u4e0d\u8bba\u4e2d\u82f1\u6587\u62ec\u53f7\n    \u8fd4\u56de\u53bb\u9664\u62ec\u53f7\u5185\u5bb9\u7684\u65b0\u5b57\u7b26\u4e32\uff0c\u4ee5\u53ca\u62ec\u53f7\u5185\u5bb9\u7684\u96c6\u5408\n    :param string:\n    :return:\n    &quot;&quot;&quot;\n    # \u5904\u7406\u25b3\u7b26\u53f7\/&#039;\u5176\u4e2d\uff1a&#039;\n    string = string.replace(&quot;\u25b3&quot;, &#039;&#039;).replace(&quot;\u5176\u4e2d\uff1a&quot;, &#039;&#039;)\n    pattern = r&#039;[(\uff08].+?[)\uff09]&#039;\n    matches = re.findall(pattern, string)\n    remarks = &#039;&#039;.join(matches)\n    for matche in matches:\n        string = string.replace(matche, &#039;&#039;)\n    return string, remarks\n\nclass AnalysisExcel:\n    def __init__(self, file_root):\n        # self.file_root = config.FILES_PATH\n        self.excel_file_list = []\n        self.file_root = file_root\n        self.output_list = []\n        self.id = 1\n    def analysis_excel(self, path):\n        suffix = path.split(&#039;.&#039;)[-1]\n        if suffix.lower() == &#039;xlsx&#039;:\n            df = pd.read_excel(path, engine=&quot;openpyxl&quot;, sheet_name=0)\n        else:\n            df = pd.read_excel(path, engine=&quot;xlrd&quot;, sheet_name=0)\n        total_raws_num = df.shape[0]\n        try:\n            row_number = [index for index, row in df.iterrows() if &#039;\u7d2f\u8ba1&#039; in str(row.values)][0]\n        except ValueError:\n            raise ValueError(&quot;\u9996\u884c\u8bfb\u53d6\u9519\u8bef\u3002\u672a\u627e\u5230&#039;\u7d2f\u8ba1&#039;\u51fa\u73b0\u7684\u9996\u884c&quot;)\n        # \u83b7\u53d6\u516c\u53f8\u540d\u79f0\n        companys = df.iloc[row_number - 1, 0]\n        if &#039;:&#039; in companys:\n            company_name = companys.split(&#039;:&#039;)[-1]\n        elif &#039;\uff1a&#039; in companys:\n            company_name = companys.split(&#039;\uff1a&#039;)[-1]\n        else:\n            company_name = companys\n        # \u83b7\u53d6\u5e74\u6708\u5b57\u6bb5\n        dates = df.iloc[row_number - 1, 2]\n        pattern = r&#039;(\\d{4})\u5e74(\\d{1,2})\u6708&#039;\n\n        def add_zero(match):\n            # \u81ea\u5b9a\u4e49\u66ff\u6362\u51fd\u6570\u6765\u786e\u4fdd\u6708\u4efd\u4e3a\u4e24\u4f4d\u6570\u5b57\n            return f&quot;{match.group(1)}-{match.group(2).zfill(2)}&quot;\n        years_days = re.sub(pattern, add_zero, dates)\n        # \u83b7\u53d6\u5176\u4ed6\u5b57\u6bb5\n        report_type = &#039;&#039;\n        first_category_name = &#039;&#039;\n        second_category_name = &#039;&#039;\n        for raw_num in range(row_number + 1, total_raws_num):\n            try:\n                item = {}\n                # item = {&#039;id&#039;: &quot;&quot;}\n                # \u516c\u53f8\u540d\u79f0\n                item[&#039;\u516c\u53f8&#039;] = company_name.strip()\n                # \u83b7\u53d6\u4ea7\u4e1a\u540d\u79f0\n                item[&#039;\u4ea7\u4e1a&#039;] = industry_mapping(item[&#039;\u516c\u53f8&#039;])\n                # \u5e74\u6708\n                item[&#039;\u5e74\u6708&#039;] = years_days\n                # \u6309&quot;\u4e0a\u5e74\u540c\u671f&quot;\u662f\u5426\u6709\u503c\u4f5c\u7ed3\u675f\u6807\u51c6\n                try:\n                    if math.isnan(df.iloc[raw_num, 4]) and math.isnan(df.iloc[raw_num, 1]):\n                        break\n                except:\n                    pass\n                first_column = df.iloc[raw_num, 0].strip()  # \u7b2c\u4e00\u5217\u5b57\u6bb5\u5185\u5bb9\n                # \u62a5\u8868\u7c7b\u578b\u5904\u7406\n                if [keyword for keyword in [&#039;\u4e00\u3001&#039;, &#039;\u4e8c\u3001&#039;, &#039;\u4e09\u3001&#039;, &#039;\u56db\u3001&#039;, &#039;\u4e94\u3001&#039;, &#039;\u516d\u3001&#039;, &#039;\u4e03\u3001&#039;, &#039;\u516b\u3001&#039;, &#039;\u4e5d\u3001&#039;, &#039;\u5341\u3001&#039;] if\n                    keyword in first_column]:\n                    report_type = first_column.split(&#039;\u3001&#039;)[-1].strip()\n                    continue\n                # \u4e00\u7ea7\u7c7b\u76ee\u540d\u79f0\n                elif [keyword for keyword in [&#039;0.&#039;, &#039;1.&#039;, &#039;2.&#039;, &#039;3.&#039;, &#039;4.&#039;, &#039;5.&#039;, &#039;6.&#039;, &#039;7.&#039;, &#039;8.&#039;, &#039;9.&#039;] if\n                      keyword in first_column]:\n                    first_category_name = first_column.split(&#039;.&#039;)[-1].strip()\n                    first_category_name, remarks = processing_bracket(first_category_name)\n\n                else:\n                    # \u4e8c\u7ea7\u7c7b\u76ee\u540d\u79f0\n                    second_category_name = first_column.strip()\n                    # \u5904\u7406\u62ec\u53f7\u5185\u5bb9\n                    second_category_name, remarks = processing_bracket(second_category_name)\n                # id\n                # item[&#039;id&#039;] = str(self.id)\n                # \u7c7b\u76ee\u540d\u79f0\n                item[&#039;\u62a5\u8868\u7c7b\u578b&#039;] = report_type\n                item[&#039;\u4e00\u7ea7\u7c7b\u76ee\u540d\u79f0&#039;] = first_category_name\n                item[&#039;\u4e8c\u7ea7\u7c7b\u76ee\u540d\u79f0&#039;] = second_category_name\n                item[&#039;\u7c7b\u76ee\u540d\u79f0&#039;] = second_category_name if second_category_name else first_category_name\n                # \u5907\u6ce8\n                item[&#039;\u5907\u6ce8&#039;] = remarks\n                # \u672c\u6708\u6570\n                number_of_current_month = df.iloc[raw_num, 2]\n                item[&#039;\u672c\u6708\u6570&#039;] = &quot;%.2f&quot; % 0 if &quot;\u2014&quot; in str(\n                    number_of_current_month) else &quot;%.2f&quot; % number_of_current_month\n                # \u672c\u5e74\u7d2f\u8ba1\n                current_year_cumulative = df.iloc[raw_num, 3]\n                item[&#039;\u672c\u5e74\u7d2f\u8ba1&#039;] = &quot;%.2f&quot; % 0 if &quot;\u2014&quot; in str(\n                    current_year_cumulative) else &quot;%.2f&quot; % current_year_cumulative\n                # \u4e0a\u5e74\u540c\u671f\n                the_same_period_of_last_year = df.iloc[raw_num, 4]\n                item[&#039;\u4e0a\u5e74\u540c\u671f&#039;] = &quot;%.2f&quot; % 0 if &quot;\u2014&quot; in str(\n                    the_same_period_of_last_year) else &quot;%.2f&quot; % the_same_period_of_last_year\n                # \u66f4\u65b0\u65f6\u95f4\n                item[&#039;\u66f4\u65b0\u65f6\u95f4&#039;] = str(datetime.datetime.now())[:19]\n                # print(json.dumps(item, indent=4, ensure_ascii=False))\n                # \u5b58\u50a8\u6570\u636e\u5165\u5e93\n                self.output_list.append(item)\n                # self.id += 1\n            except Exception as e:\n                logger.error(e)\n\n    # def to_database(self, item):\n    #     ZhongChe.create(**item)\n\n    def get_file_list(self, path):\n        &quot;&quot;&quot;\n        \u83b7\u53d6excel\u6587\u4ef6\u5217\u8868\n        :param path:\n        :return:\n        &quot;&quot;&quot;\n        files = os.listdir(path)\n        for file in files:\n            # \u62fc\u63a5\u6587\u4ef6\u7684\u5b8c\u6574\u8def\u5f84\n            file_path = os.path.join(path, file)\n            # \u5224\u65ad\u6587\u4ef6\u7c7b\u578b\n            if os.path.isfile(file_path):  # \u662f\u5426\u662f\u6587\u4ef6\n                logger.info(file_path)\n                suffix = file_path.split(&#039;.&#039;)[-1]\n                if suffix == &#039;zip&#039;:\n                    logger.info(&quot;\u5f53\u524d\u6587\u4ef6\u4e3a\u538b\u7f29\u4ef6\uff0c\u8fdb\u884c\u89e3\u538b\u64cd\u4f5c...&quot;)\n                    zip_file_path = file_path\n                    target_path = &#039;&#039;.join(file_path.split(&#039;.&#039;)[:-1])\n                    # \u6253\u5f00ZIP\u6587\u4ef6\n                    zip_file = zipfile.ZipFile(zip_file_path)\n                    # \u89e3\u538b\u6240\u6709\u6587\u4ef6\u5230\u76ee\u6807\u8def\u5f84\uff0c\u5e76\u6307\u5b9a\u6587\u4ef6\u540d\u7f16\u7801\n                    for file_info in zip_file.infolist():\n                        file_info.filename = file_info.filename.encode(&#039;cp437&#039;).decode(&#039;gbk&#039;, errors=&#039;ignore&#039;)\n                        zip_file.extract(file_info, target_path)\n                    # \u5173\u95edZIP\u6587\u4ef6\n                    zip_file.close()\n                    # \u518d\u6b21\u904d\u5386\u8be5\u8def\u5f84\n                    self.get_file_list(target_path)\n                elif suffix.lower() == &#039;xlsx&#039; or suffix.lower() == &#039;xls&#039;:\n                    self.excel_file_list.append(file_path)\n                else:\n                    ...\n                    logger.error(FileNotFoundError(&quot;\uff01\uff01\u6587\u4ef6\u7c7b\u578b\u9519\u8bef\uff01\uff01\u6587\u4ef6\u975ezip\u6216xlsx\/xls\u683c\u5f0f\uff01&quot;))\n            else:\n                self.get_file_list(file_path)\n\n    def main(self):\n        &quot;&quot;&quot;\n        \u8bfb\u53d6\u6587\u4ef6\u8def\u5f84\n        :return:\n        &quot;&quot;&quot;\n        # \u83b7\u53d6\u6587\u4ef6\u5217\u8868\n        self.get_file_list(self.file_root)\n        # self.excel_file_list = list(set(self.excel_file_list))\n        print(json.dumps(self.excel_file_list, ensure_ascii=False, indent=4))\n        # \u89e3\u6790\u6587\u4ef6\n        for excel_file_path in self.excel_file_list:\n            self.analysis_excel(excel_file_path)\n        return self.output_list\n\nif __name__ == &#039;__main__&#039;:\n    # file_path = r&#039;\/home\/rhino\/zhongche_data\/&#039;\n    file_path = r&quot;D:\\workspace\\\u9a71\u52a8\u53ca\u811a\u672c\\\u5c71\u4e1c\u4e2d\u8f66\u9879\u76ee\u652f\u6301\\\u65b0\u5efa\u6587\u4ef6\u5939&quot;\n    output_list = AnalysisExcel(file_root=file_path).main()\n    # key_names = [&#039;\u516c\u53f8&#039;.encode(&quot;GBK&quot;).decode(&quot;GBK&quot;), &#039;industry&#039;, &#039;years_days&#039;, &#039;report_type&#039;, &#039;first_category_name&#039;, &#039;second_category_name&#039;,\n    #  &#039;category_name&#039;, &#039;number_of_current_month&#039;, &#039;current_year_cumulative&#039;, &#039;the_same_period_of_last_year&#039;, &#039;remarks&#039;,\n    #  &#039;update_time&#039;]\n    # pd.set_option(&#039;display.unicode.east_asian_width&#039;, False)\n    key_names = [&#039;\u516c\u53f8&#039;, &#039;\u4ea7\u4e1a&#039;, &#039;\u5e74\u6708&#039;, &#039;\u62a5\u8868\u7c7b\u578b&#039;, &#039;\u4e00\u7ea7\u7c7b\u76ee\u540d\u79f0&#039;, &#039;\u4e8c\u7ea7\u7c7b\u76ee\u540d\u79f0&#039;, &#039;\u7c7b\u76ee\u540d\u79f0&#039;, &#039;\u672c\u6708\u6570&#039;, &#039;\u672c\u5e74\u7d2f\u8ba1&#039;, &#039;\u4e0a\u5e74\u540c\u671f&#039;, &#039;\u5907\u6ce8&#039;, &#039;\u66f4\u65b0\u65f6\u95f4&#039;]\n    output_dataframe = pd.DataFrame(output_list, columns=key_names)\n    # output_dataframe.to_excel()\n    print(output_dataframe)\n<\/code><\/pre>\n","protected":false},"excerpt":{"rendered":"<p># -*- coding: UTF-8 -*- &quot;&quot;&quot;==========================   \u2026 &#8230;<\/p>\n","protected":false},"author":1,"featured_media":0,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"ngg_post_thumbnail":0},"categories":[48],"tags":[83,217],"_links":{"self":[{"href":"\/index.php?rest_route=\/wp\/v2\/posts\/9028"}],"collection":[{"href":"\/index.php?rest_route=\/wp\/v2\/posts"}],"about":[{"href":"\/index.php?rest_route=\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"\/index.php?rest_route=\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"\/index.php?rest_route=%2Fwp%2Fv2%2Fcomments&post=9028"}],"version-history":[{"count":1,"href":"\/index.php?rest_route=\/wp\/v2\/posts\/9028\/revisions"}],"predecessor-version":[{"id":9029,"href":"\/index.php?rest_route=\/wp\/v2\/posts\/9028\/revisions\/9029"}],"wp:attachment":[{"href":"\/index.php?rest_route=%2Fwp%2Fv2%2Fmedia&parent=9028"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"\/index.php?rest_route=%2Fwp%2Fv2%2Fcategories&post=9028"},{"taxonomy":"post_tag","embeddable":true,"href":"\/index.php?rest_route=%2Fwp%2Fv2%2Ftags&post=9028"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}