Excel用正则表达式提取出输入正确的身份证号

本文介绍如何使用Excel配合方方格子插件通过正则表达式筛选并提取正确的身份证号码,具体步骤包括选择插件中的正则表达式操作及输入特定的正则表达式。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

今天小编帮助客户整理了一堆省份证号,如下图所示,这里为了做演示输入了一些虚拟号,想要分享的是Excel用正则表达式提取出输入正确的身份证号

(方方格子插件)

1.先看动图演示吧

 

2.那我了对比我们可以先把一堆身份证号复制一列出来

3.然后在选中数据的同时选择方方格子按钮

4.选择其中的更多操作

5.选择正则表达式操作命令

6.弹出界面选择提取按钮,并输入正则表达式^((\d{18})|([0-9x]{18})|([0-9X]{18}))$

7.确定后即可看到正确的正则表达式被保留了

如果经验帮到了你,请记得分享!

<think>我们已经在之前的代码中实现了读取指定列的功能。但是,根据用户的问题,他们可能希望更详细地了解如何在现有代码中添加这个功能。因此,我将重新组织一下,重点说明如何修改现有代码以支持读取指定列,并给一个更通用的函数。 根据引用[1],我们可以通过设置`engine='openpyxl'`来避免警告,并且使用`pandas.read_excel`读取Excel文件。 现有代码中,我们已经有一个函数`extract_columns`,它可以根据列名或列索引提取列。现在,假设用户有一个现有的数据处理流程,并希望在这个流程中添加提取指定列的功能。 以下是一个示例,展示如何将指定列读取功能集成到现有代码中: 步骤: 1. 读取Excel文件时,可以只读取需要的列,以减少内存使用(使用`usecols`参数)。 2. 在后续的数据处理中,只处理这些列。 修改后的函数可以这样写: ```python import pandas as pd def read_specific_columns(input_file, columns_to_extract, sheet_name=0): """ 读取Excel文件中的指定列 参数: input_file: 输入Excel文件路径 columns_to_extract: 要提取的列,可以是列名的列表或列索引的列表(从0开始) sheet_name: 要读取的工作表,默认为第一个工作表 返回: 包含指定列的DataFrame """ # 判断是列名还是列索引 if all(isinstance(col, int) for col in columns_to_extract): # 如果是列索引,我们可以通过usecols参数指定列索引(注意:openpyxl的列索引从0开始) # 注意:usecols参数也可以接受整数列表,表示列索引(但注意,这里读取的是列的位置,不包括索引0的第一列?) # 实际上,在pandas中,usecols的整数列表表示列的位置(0-indexed) df = pd.read_excel(input_file, sheet_name=sheet_name, engine='openpyxl', usecols=columns_to_extract) elif all(isinstance(col, str) for col in columns_to_extract): # 如果是列名,直接传入列名列表 df = pd.read_excel(input_file, sheet_name=sheet_name, engine='openpyxl', usecols=columns_to_extract) else: raise ValueError("列参数必须全部为整数索引或全部为字符串列名") return df # 示例:在现有数据处理流程中使用 if __name__ == "__main__": # 假设现有流程中读取整个文件 # 原始方式:df = pd.read_excel("原始数据.xlsx") # 现在改为只读取指定列 input_file = "原始数据.xlsx" output_file = "处理后的数据.xlsx" # 定义要提取的列(按列名或列索引) # 方式1:按列名 # columns_to_extract = ["产品名称", "价格", "库存量"] # 方式2:按列索引(注意:这里列索引0表示第一列) columns_to_extract = [0, 2, 3] # 提取第一列、第三列和第四列 # 读取指定列 df_selected = read_specific_columns(input_file, columns_to_extract) # 后续处理(例如数据清洗、计算等) # ... 这里可以添加你的数据处理代码 ... # 保存到新文件 df_selected.to_excel(output_file, index=False) print(f"已保存处理后的数据到 {output_file}") ``` ### 说明: 1. **使用`usecols`参数**:在读取Excel文件时,通过`usecols`参数指定要读取的列,可以避免读取不需要的列,从而节省内存并提高读取速度[^1]。 2. **列索引与列名**:函数支持两种方式指定列:列名(字符串列表)或列索引(整数列表,从0开始)。 3. **错误处理**:如果传入的列参数既包含字符串又包含整数,函数会抛异常。 ### 注意事项: - 当使用列索引时,`usecols`参数接受整数列表,这些整数对应于Excel文件中的列位置(0表示第一列)。 - 当使用列名时,确保列名在Excel文件中存在,否则会抛错误。 ### 在现有代码中添加此功能: 如果你的现有代码已经读取了整个Excel文件,并且你想修改为只读取指定列,那么只需将原来的`pd.read_excel`调用替换为`read_specific_columns`函数即可。 ### 高级应用:条件读取 如果你需要根据列名动态选择列(例如,根据配置文件或用户输入),你可以这样调用函数: ```python # 从配置文件中读取列名 # 假设config是一个字典,其中包含'required_columns'键,值为列名的列表 config = {'required_columns': ['姓名', '年龄', '城市']} df = read_specific_columns('数据.xlsx', config['required_columns']) ``` ### 处理多个工作表 如果你的Excel文件有多个工作表,并且你想从每个工作表中读取相同的列,可以使用以下方法: ```python def read_specific_columns_multisheet(input_file, columns_to_extract): # 读取所有工作表 all_sheets = pd.read_excel(input_file, sheet_name=None, engine='openpyxl') result_dfs = {} for sheet_name, df in all_sheets.items(): # 对每个工作表选择指定列 if all(isinstance(col, int) for col in columns_to_extract): selected = df.iloc[:, columns_to_extract] else: selected = df[columns_to_extract] result_dfs[sheet_name] = selected return result_dfs ``` ### 性能优化 对于非常大的Excel文件,使用`usecols`只读取需要的列可以显著减少内存使用和读取时间。 ### 相关问题 §§相关问题§§ 1. 如何从Excel提取满足特定条件的行并保存到新文件? 2. Pandas处理大型Excel文件时如何优化内存使用? 3. 如何将多个Excel文件的指定列合并到一个文件中? 4. 如何处理Excel中的日期格式数据? 5. 如何将提取的数据直接导入数据库进行分析?</think># 在Python中添加Excel指定列读取功能 根据您的需求,我将展示如何在现有Python代码中添加功能以读取Excel文件中的指定列并进行数据处理。参考引用[1]中提到的技术,我们将使用`pandas`库和`openpyxl`引擎来实现这一功能。 ## 添加指定列读取功能的完整方案 ### 1. 基础功能实现 ```python import pandas as pd def read_specific_columns(input_file, columns_to_extract, sheet_name=0): """ 读取Excel文件中指定列的数据 参数: input_file: Excel文件路径 columns_to_extract: 要提取的列名列表或列索引列表 sheet_name: 要读取的工作表名称或索引(默认为第一个工作表) 返回: 包含指定列的DataFrame """ # 使用openpyxl引擎读取Excel文件,避免警告[^1] df = pd.read_excel(input_file, sheet_name=sheet_name, engine='openpyxl') # 判断输入类型:列名列表或列索引列表 if all(isinstance(col, int) for col in columns_to_extract): # 使用列索引选择列 selected_columns = df.iloc[:, columns_to_extract] elif all(isinstance(col, str) for col in columns_to_extract): # 使用列名选择列 selected_columns = df[columns_to_extract] else: raise ValueError("列参数必须全部为整数索引或全部为字符串列名") return selected_columns # 使用示例 if __name__ == "__main__": input_file = "销售数据.xlsx" # 方式1: 按列名提取 columns_by_name = ["产品名称", "数量", "总价"] data_by_name = read_specific_columns(input_file, columns_by_name) # 方式2: 按列索引提取(索引从0开始) columns_by_index = [2, 3, 5] # 提取第3、4、6列 data_by_index = read_specific_columns(input_file, columns_by_index) # 显示结果 print("按列名提取结果:") print(data_by_name.head()) print("\n按列索引提取结果:") print(data_by_index.head()) ``` ### 2. 集成到现有数据处理流程 假设您已有数据处理流程,以下是添加指定列读取功能的示例: ```python import pandas as pd import numpy as np def process_data(input_file, output_file, columns_to_extract): """ 完整数据处理流程:读取指定列 -> 数据处理 -> 保存结果 参数: input_file: 输入Excel文件路径 output_file: 输Excel文件路径 columns_to_extract: 要提取的列名列表或列索引列表 """ # 1. 读取指定列 df = read_specific_columns(input_file, columns_to_extract) # 2. 数据处理示例:计算平均销售额 if "总价" in df.columns or (isinstance(columns_to_extract[0], int) and len(columns_to_extract) > 2): # 假设总价在最后一列 total_price_col = df.columns[-1] if isinstance(columns_to_extract[0], str) else df.columns[2] df["平均销售额"] = df[total_price_col] / df["数量"] if "数量" in df.columns else df[total_price_col] # 3. 保存处理结果 df.to_excel(output_file, index=False) print(f"数据处理完成,结果已保存至 {output_file}") return df # 使用示例 if __name__ == "__main__": input_file = "销售数据.xlsx" output_file = "处理结果.xlsx" columns_to_extract = ["产品名称", "数量", "总价"] result = process_data(input_file, output_file, columns_to_extract) print("\n处理结果预览:") print(result.head()) ``` ### 3. 高级功能:动态列选择与处理 ```python def dynamic_column_processing(input_file, column_config): """ 根据配置动态选择和处理列数据 参数: input_file: Excel文件路径 column_config: 列配置字典,格式为: { "include_columns": ["产品名称", "数量", "总价"], # 需要包含的列 "exclude_columns": ["客户ID"], # 需要排除的列 "transformations": { # 列转换规则 "总价": lambda x: x * 0.9, # 打9折 "数量": lambda x: x.astype(float) # 转换为浮点数 } } """ # 读取整个文件 df = pd.read_excel(input_file, engine='openpyxl') # 确定最终要包含的列 if "include_columns" in column_config: selected_columns = [col for col in column_config["include_columns"] if col not in column_config.get("exclude_columns", [])] else: # 如果没有指定包含列,则排除指定列 selected_columns = [col for col in df.columns if col not in column_config.get("exclude_columns", [])] # 选择指定列 df_selected = df[selected_columns] # 应用列转换 transformations = column_config.get("transformations", {}) for col, func in transformations.items(): if col in df_selected.columns: df_selected[col] = df_selected[col].apply(func) return df_selected # 使用示例 if __name__ == "__main__": input_file = "销售数据.xlsx" column_config = { "include_columns": ["订单ID", "产品名称", "数量", "总价"], "exclude_columns": ["订单ID"], "transformations": { "总价": lambda x: x * 0.9, # 应用9折 "数量": lambda x: float(x) # 转换为浮点数 } } processed_data = dynamic_column_processing(input_file, column_config) print("动态列处理结果:") print(processed_data.head()) ``` ## 功能说明与最佳实践 ### 1. 列选择方式比较 | **选择方式** | **优点** | **缺点** | **适用场景** | |------------|---------|---------|------------| | **列名选择** | 代码可读性高,列名变更时代码更健壮 | 需要准确知道列名 | 列名明确且不会频繁变更 | | **列索引选择** | 不依赖列名,处理未知结构文件更灵活 | 列顺序变更会导致错误 | 处理结构未知或列名复杂的文件 | | **动态配置** | 高度灵活,可适应不同需求 | 配置复杂,需要额外处理逻辑 | 需要根据不同条件处理不同列 | ### 2. 性能优化技巧 - **只读取需要的列**:使用`usecols`参数减少内存占用 ```python # 只读取指定列,提高性能 df = pd.read_excel(input_file, usecols=columns_to_extract, engine='openpyxl') ``` - **分块处理大型文件**: ```python chunk_size = 1000 # 每次处理1000行 reader = pd.read_excel(input_file, chunksize=chunk_size, engine='openpyxl') for chunk in reader: # 处理每个数据块中的指定列 selected_chunk = chunk[columns_to_extract] # 进行后续处理... ``` ### 3. 错误处理与数据验证 ```python def safe_read_columns(input_file, columns_to_extract): """带错误处理的列读取函数""" try: df = pd.read_excel(input_file, engine='openpyxl') # 验证列是否存在 if isinstance(columns_to_extract[0], str): missing_cols = [col for col in columns_to_extract if col not in df.columns] if missing_cols: print(f"警告: 以下列不存在 - {', '.join(missing_cols)}") # 只保留存在的列 columns_to_extract = [col for col in columns_to_extract if col in df.columns] # 选择列 return df[columns_to_extract] if isinstance(columns_to_extract[0], str) else df.iloc[:, columns_to_extract] except FileNotFoundError: print(f"错误: 文件 {input_file} 不存在") return pd.DataFrame() except Exception as e: print(f"处理文件时错: {str(e)}") return pd.DataFrame() ``` ## 实际应用场景 ### 1. 销售数据分析 ```python def analyze_sales_data(input_file): """分析销售数据中的关键指标""" # 提取关键列 columns = ["产品名称", "数量", "单价", "总价"] sales_data = read_specific_columns(input_file, columns) # 计算总销售额 total_sales = sales_data["总价"].sum() # 计算最畅销产品 best_seller = sales_data.groupby("产品名称")["数量"].sum().idxmax() # 计算平均单价 avg_price = sales_data["单价"].mean() print(f"总销售额: ¥{total_sales:,.2f}") print(f"最畅销产品: {best_seller}") print(f"平均单价: ¥{avg_price:,.2f}") return sales_data ``` ### 2. 客户数据提取 ```python def extract_customer_info(input_file, output_file): """从原始数据中提取客户信息并保存""" # 提取客户相关列 customer_columns = ["客户ID", "姓名", "邮箱", "电话", "注册日期"] customer_data = read_specific_columns(input_file, customer_columns) # 数据清洗:移除重复项 customer_data = customer_data.drop_duplicates(subset="客户ID") # 保存到新文件 customer_data.to_excel(output_file, index=False) print(f"客户信息已保存至 {output_file}") return customer_data ``` ### 3. 财务数据处理 ```python def process_financial_data(input_file, output_file): """处理财务报表中的关键列""" # 提取财务相关列 financial_columns = ["科目代码", "科目名称", "期初余额", "本期借方", "本期贷方", "期末余额"] financial_data = read_specific_columns(input_file, financial_columns) # 计算验证:期初余额 + 本期借方 - 本期贷方 = 期末余额 financial_data["计算期末余额"] = financial_data["期初余额"] + financial_data["本期借方"] - financial_data["本期贷方"] # 标记不平衡的记录 financial_data["平衡状态"] = np.where( abs(financial_data["期末余额"] - financial_data["计算期末余额"]) < 0.01, "平衡", "不平衡" ) # 保存结果 financial_data.to_excel(output_file, index=False) return financial_data ``` ## 常见问题解决 1. **列名包含特殊字符或空格**: ```python # 使用原始列名或重命名列 df = df.rename(columns={"Product Name": "产品名称", "Unit Price": "单价"}) columns_to_extract = ["产品名称", "单价"] ``` 2. **处理日期格式列**: ```python # 读取时指定日期解析 df = pd.read_excel(input_file, parse_dates=["订单日期"], engine='openpyxl') ``` 3. **处理大型文件内存不足**: ```python # 仅读取需要的列和行范围 df = pd.read_excel(input_file, usecols=columns_to_extract, nrows=10000, engine='openpyxl') ``` 4. **处理多个工作表的指定列**: ```python def read_sheets_columns(input_file, columns_to_extract): """读取所有工作表的指定列""" # 读取所有工作表 sheets_dict = pd.read_excel(input_file, sheet_name=None, engine='openpyxl') result = {} for sheet_name, df in sheets_dict.items(): # 提取指定列 if isinstance(columns_to_extract[0], str): result[sheet_name] = df[columns_to_extract] else: result[sheet_name] = df.iloc[:, columns_to_extract] return result ``` 通过以上方法,您可以在现有Python代码中灵活添加Excel指定列读取功能,并根据需要进行各种数据处理操作。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值