数据分析:数据分割

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

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 小时前
[Pytest] [Part 2]增加 log功能
开发语言·python·pytest
漫谈网络2 小时前
WebSocket 在前后端的完整使用流程
javascript·python·websocket
try2find3 小时前
安装llama-cpp-python踩坑记
开发语言·python·llama
DataGear3 小时前
如何在DataGear 5.4.1 中快速制作SQL服务端分页的数据表格看板
javascript·数据库·sql·信息可视化·数据分析·echarts·数据可视化
博观而约取4 小时前
Django ORM 1. 创建模型(Model)
数据库·python·django
王小王-1235 小时前
基于Hadoop的京东厨具商品数据分析及商品价格预测系统的设计与实现
hadoop·数据分析·京东厨具·厨具分析·商品分析
精灵vector6 小时前
构建专家级SQL Agent交互
python·aigc·ai编程
Zonda要好好学习6 小时前
Python入门Day2
开发语言·python
Vertira6 小时前
pdf 合并 python实现(已解决)
前端·python·pdf
太凉6 小时前
Python之 sorted() 函数的基本语法
python