数据分析:数据分割

分享一个数据分割的代码,第一次分割按照数字,第二次分割按照空格和汉字

python 复制代码
import pandas as pd  
import re  
  
# 指定文件路径  
file_path = 'C:\\Users\\admin\\Desktop\\tumi.xlsx'  
  
# 使用pandas的read_excel函数读取Excel文件  
df = pd.read_excel(file_path, engine='openpyxl')  
  
# 查看第一列的数据  
first_column_data = df.iloc[:, 0]  
  
# 定义一个函数,使用'0'作为分隔符来拆分字符串,只拆分一次  
def split_once_by_zero(text):  
    if isinstance(text, str):  
        parts = text.split('0', 1)  # 只拆分第一次出现的'0'  
        if len(parts) == 1:  
            return [parts[0], None]  # 如果没有'0',则返回原字符串和None  
        else:  
            return parts  # 返回拆分后的两部分  
    else:  
        return [None, None]  # 非字符串情况返回两个None  
  
# 应用拆分函数到第一列数据  
split_data = first_column_data.apply(split_once_by_zero)  
  
# 初始化新DataFrame,只有两列  
split_df = pd.DataFrame({  
    '字段1': [item[0] for item in split_data],  
    '字段2_临时': ['0' + item[1] if item[1] is not None else None for item in split_data]  
}, index=df.index)  
  
# 定义一个正则表达式,用于匹配非汉字和非特殊字符的部分  
# 汉字通常落在Unicode范围\u4e00-\u9fa5内,特殊字符可根据需要自行添加  
pattern = r'([^\u4e00-\u9fa5^!@#$%^&*()_+\-=\[\]{};\':"\\|,.<>\/?]+)'  
  
# 定义一个函数,用于拆分字段2_临时,基于正则表达式  
def split_by_regex(text):  
    if text is None:  
        return [None, None]  
    matches = re.split(pattern, text)  
    # 过滤掉空字符串  
    matches = [m for m in matches if m]  
    if len(matches) == 1:  
        return [text, None]  # 如果没有匹配到,返回原字符串和None  
    else:  
        return [matches[0], ''.join(matches[1:])]  # 返回拆分后的两部分  
  
# 应用拆分函数到字段2_临时  
split_df[['字段2', '字段3']] = pd.DataFrame(split_df['字段2_临时'].apply(split_by_regex).tolist(), index=split_df.index)  
  
# 删除临时的字段2列  
del split_df['字段2_临时']  
  
# 显示拆分后的DataFrame  
print(split_df)  
  
# 指定新的Excel文件路径  
output_file_path = 'C:\\Users\\admin\\Desktop\\split_tumi_twice.xlsx'  
  
# 使用Pandas的to_excel方法保存DataFrame到Excel文件  
split_df.to_excel(output_file_path, index=False)  # 不保存索引到Excel文件中
相关推荐
曲幽1 小时前
FastAPI + PostgreSQL 实战:给应用装上“缓存”和“日志”翅膀
redis·python·elasticsearch·postgresql·logging·fastapi·web·es·fastapi-cache
Lupino4 小时前
别再只聊 AI 写代码了:技术负责人要把“变更治理”提到第一优先级
python·docker·容器
Flittly5 小时前
【从零手写 ClaudeCode:learn-claude-code 项目实战笔记】(6)Context Compact (上下文压缩)
python·agent
曲幽16 小时前
FastAPI + PostgreSQL 实战:从入门到不踩坑,一次讲透
python·sql·postgresql·fastapi·web·postgres·db·asyncpg
用户83562907805121 小时前
使用 C# 在 Excel 中创建数据透视表
后端·python
码路飞1 天前
FastMCP 实战:一个 .py 文件,给 Claude Code 装上 3 个超实用工具
python·ai编程·mcp
dev派1 天前
AI Agent 系统中的常用 Workflow 模式(2) Evaluator-Optimizer模式
python·langchain
前端付豪1 天前
AI 数学辅导老师项目构想和初始化
前端·后端·python
用户0332126663671 天前
将 PDF 文档转换为图片【Python 教程】
python
悟空爬虫1 天前
UV实战教程,我啥要从Anaconda切换到uv来管理包?
python