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

求与Python pandas DataFrame处理代码等价的JavaScript实现

等价的JavaScript实现

你可以用Danfo.js(Pandas的JavaScript等价库)实现和你Python代码完全一致的逻辑,也可以用原生JavaScript直接处理。以下是两种方案:

方案一:基于Danfo.js实现

Danfo.js的API设计和Pandas高度相似,能直接对应你的代码逻辑:

function sortDf(datas) {
  // 读取JSON字符串为DataFrame
  const dfNotSorted = danfo.readJSON(datas);
  
  // 处理Date列:去除每个日期的Z后缀并解析为日期对象
  dfNotSorted.addColumn("Date", dfNotSorted["Date"].apply((dates) => {
    return dates.map(dateStr => {
      const trimmedDate = dateStr.endsWith('Z') ? dateStr.slice(0, -1) : dateStr;
      return new Date(trimmedDate);
    });
  }), { inplace: true });
  
  // 处理time列:转为日期类型并移除时区信息
  dfNotSorted.addColumn("time", dfNotSorted["time"].apply((timeStr) => {
    const date = new Date(timeStr);
    // 移除时区,转为本地时间的Date对象(等价于tz_localize(None))
    return new Date(date.getFullYear(), date.getMonth(), date.getDate(), 
                    date.getHours(), date.getMinutes(), date.getSeconds(), 
                    date.getMilliseconds());
  }), { inplace: true });
  
  // 设置复合索引并按索引排序
  const df = dfNotSorted.setIndex({ keys: ["Bus", "time"] }).sortIndex();
  
  return df;
}

对应关系说明

  • danfo.readJSON(datas) → 对应pd.read_json(StringIO(datas))
  • Date列的apply逻辑 → 对应原代码中lambda dates: [datetime.fromisoformat(date.rstrip('Z')) for date in dates]
  • time列的处理 → 对应pd.to_datetime + tz_localize(None)
  • setIndex + sortIndex → 和原代码完全一致的复合索引排序逻辑

方案二:原生JavaScript实现

如果不想依赖第三方库,直接操作JSON数组也能实现相同效果:

function sortDf(datas) {
  // 解析JSON为数组对象
  let data = JSON.parse(datas);
  
  // 处理Date列
  data = data.map(item => {
    item.Date = item.Date.map(dateStr => {
      const trimmed = dateStr.endsWith('Z') ? dateStr.slice(0, -1) : dateStr;
      return new Date(trimmed);
    });
    return item;
  });
  
  // 处理time列,移除时区信息
  data = data.map(item => {
    const timeDate = new Date(item.time);
    item.time = new Date(timeDate.getFullYear(), timeDate.getMonth(), timeDate.getDate(), 
                        timeDate.getHours(), timeDate.getMinutes(), timeDate.getSeconds(), 
                        timeDate.getMilliseconds());
    return item;
  });
  
  // 按Bus和time复合排序
  data.sort((a, b) => {
    // 先按Bus字段排序
    if (a.Bus !== b.Bus) {
      return a.Bus.localeCompare(b.Bus);
    }
    // Bus相同时按time排序
    return a.time - b.time;
  });
  
  return data;
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.07 16:13:09