数据分析:数据分割

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

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文件中
相关推荐
spencer_tseng18 分钟前
[j2cache ehcache.xml]/tmp/.ehcache-diskstore.lock (Permission denied)
xml·linux·python·ehcache·[j2cache
梦想不只是梦与想1 小时前
Python Web 框架:FastAPI
python·fastapi·web框架
玩大数据的龙威1 小时前
农经权二轮延包—全面取代人工公示图生成
python·arcgis
IT_Octopus1 小时前
JSON 日志里的 `{“$ref“:“$.xxx“}`:从 fastjson 兼容包到原生 fastjson2 的迁移实录
开发语言·python·json
geovindu1 小时前
python:HandWriting Recognition using paddlepaddle
开发语言·后端·python·paddlepaddle
数脉2 小时前
从 0 设计一个列级数据血缘模型:我们踩过的坑与最终方案
数据分析
wuyk5552 小时前
Python 零基础入门第九章:用户输入与 While 循环
开发语言·python
兮动人2 小时前
Python变量与常量
开发语言·python·机器学习·python变量与常量
2601_962300812 小时前
机器学习的理想基石
人工智能·python·机器学习·编程语言·数据处理
Java后端的Ai之路2 小时前
21、Python - 命令模式
开发语言·人工智能·python·命令模式·外观模式