数据分析:数据分割

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

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文件中
相关推荐
观察员17 分钟前
用 Pandas 对抓取的电影数据进行分析
pandas
Data_Journal31 分钟前
如何使用 Python 抓取 Google Flights:分步指南
大数据·开发语言·数据库·python·scrapy
你我一见如故1 小时前
仿QQ音乐桌面客户端——测试报告
python·selenium
shujudang1 小时前
从数据闭环到 Agent 协同:企业营销自动化如何演进为智能运营?
大数据·运维·人工智能·数据分析·自动化
Kismet_nvi1 小时前
Python 基础核心知识点总结
开发语言·windows·python
2401_844582951 小时前
冷门技巧:AI模型可靠性测试的实用技巧:数
python
you鬰1 小时前
datawhale--llm-algo-leetcode5️⃣
python·datawhale
λqaq71 小时前
MySQL 数据库基础(2)约束、用户权限、远程连接、外键与 TCP/UDP 理解
linux·数据库·python·tcp/ip·mysql
人工干智能2 小时前
科普:pandas 时间偏移别名:ts.resample(“5Min“).sum()
python·pandas
开源量化GO2 小时前
最新AI辅助量化表达:先理清规则,再按需求选工具
人工智能·python