You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用Pandas将每行Opening Date列后首个日期移至该列

解决方案

核心思路

不用指定具体提取列的关键是先定位"Opening Date"列的位置,然后从该位置之后的列中逐行查找第一个有效日期值,再替换原"Opening Date"的内容,同时清空找到日期的那个列的值。

具体实现步骤

  1. 获取"Opening Date"列的索引位置:
opening_col_idx = df.columns.get_loc("Opening Date")
  1. 定义处理单行的函数,用于查找目标日期并更新行数据:
def fix_opening_date(row):
    # 从Opening Date列之后的所有列中遍历
    for col in row.index[opening_col_idx+1:]:
        # 尝试转换为日期,非日期值会返回NaN
        date_val = pd.to_datetime(row[col], errors='coerce')
        if not pd.isna(date_val):
            # 更新Opening Date列的值
            row["Opening Date"] = date_val
            # 清空原列的日期内容
            row[col] = pd.NA
            break
    return row
  1. 将函数应用到整个DataFrame:
df = df.apply(fix_opening_date, axis=1)

补充说明

  • 该方法完全不需要指定"Opening Date"之后的具体列名,不管后续有多少列,都会自动定位第一个有效日期。
  • 如果某行"Opening Date"之后没有有效日期,该行的"Opening Date"会保持原值不变。
  • pd.to_datetime(..., errors='coerce')能兼容绝大多数常见日期格式,确保只识别真正的日期值。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.11 07:45:29