You need to enable JavaScript to run this app. Python拼接CSV时按NAME列含'RE'条件截取子串生成DATE_TIME问题
优惠活动
大模型
产品
解决方案
定价
更多

Python拼接CSV时按NAME列含'RE'条件截取子串生成DATE_TIME问题

问题根因与修复方案

错误点说明

  • 第一,if判断逻辑错误:当前代码将整个NAME列的Series对象强制转字符串后做匹配,返回的是整个Series的打印文本(包含索引、dtype等附加信息),不可能等于RE-,所以逻辑永远走else分支。行级的条件判断不能直接用Python原生的if-else,要改用pandas的向量化条件函数。
  • 第二,切片索引错误:从给出的示例NAME字符串来看,RE-的起始位置是第22位(索引从0开始),原代码写的str[23:25]只能取到E-,永远匹配不到RE-。
  • 第三,all_df.append(df)缩进错误:原代码把这行写在for循环外,只会把最后一个读取的csv对应的df加入列表,拼接结果会丢失前面所有文件的数据。

修复后完整代码

import pandas as pd
import numpy as np
import os

path_dataset = r'C:\\Users\\test'

def get_file(path_dataset):
    files = os.listdir(path_dataset) # 读取文件列表
    files.sort() # 排序文件
    file_list = []
    for file in files:
        path = os.path.join(path_dataset, file) # 用os.path.join避免路径拼接的斜杠错误
        if (file.startswith("test")) and (file.endswith(".csv")):
            file_list.append(path)
    return file_list

read_columns = ['NAME']
read_files = get_file(path_dataset)
all_df = []

for file in read_files:
    df = pd.read_csv(file, usecols = read_columns)
    # 行级条件判断用np.where做向量化处理
    df['DATE_TIME'] = np.where(
        df['NAME'].astype(str).str[22:25] == 'RE-', # 修正切片位置判断RE-
        df['NAME'].astype(str).str[25:39], # RE存在时截取后续14位日期时间
        df['NAME'].astype(str).str[22:36] # RE不存在时截取对应位置的14位日期时间
    )
    all_df.append(df) # 修正缩进,放入for循环内

Concat_table = pd.concat(all_df, axis=0)
Concat_table = Concat_table.sort_values(['DATE_TIME'])

print(Concat_table.head())
Concat_table.to_csv(os.path.join(path_dataset, 'Concate_all.csv'), index=False)

优化建议

如果无法保证NAME前缀长度完全固定,可以用字符串包含判断替代固定位置切片判断,逻辑更鲁棒:
把np.where的判断条件替换为df['NAME'].astype(str).str.contains('RE-')即可。


内容的提问来源于stack exchange,提问作者Kelvin Lo

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.09 09:39:02