簡體   English   中英

如何獲得 JavaScript 中時間序列上兩個值之間的差異?

[英]How to get the difference between two values on a time series in JavaScript?

在 Python 中,這很容易,但在 JavaScript 中,這讓我很頭疼。

我正在使用 Chart.js、D3 和 Date-FNS。 我正在使用 CSV。 你可以在這里查看我的 CSV 文件。

我想得到每天之間的病例或死亡人數的差異,所以理論上我可以得到每天的新病例或死亡人數,而不是總病例數。 我的意思是使用算術運算符每 2 天重新采樣一次。 只是減去這讓我很頭疼。

類似於問題中 Python 的 Pandas 的diff()

有人建議我使用map()reduce() ,但沒有任何效果。

減去 JS 列中的值的啟發,我嘗試了:

  const DailyDeathsData = dates.map((d, pair) =>
  {
      var firstVal = parseInt(d.totalDeaths[pair]);
      var secondVal = parseInt(d.totalDeaths[pair + 1]);
      var daily = (firstVal > secondVal) ? firstVal - secondVal : secondVal - firstVal;
      return daily;
  });

但它返回全零。

然后,受JavaScript go 的啟發,通過數組並用 next 減去每個項目,使用slicemapreduce

const DailyDeathsData = dates.slice(1).map((v, i) => v.totalDeaths - dates[i].totalDeaths);

它還返回全零。

然后,使用reduce

const DailyDeathsData = dates.reduce((v1, v2) => { return v1.totalDeaths - v2.totalDeaths });

但它沒有顯示。

如果我正確理解您想要實現的目標,您可以執行以下操作:

 const data = [{ city: 'Aparecida', date: '2021-01-04', totalDeaths: 21, totalCases: 781, totalRecovered: 724, totalBeds: 13, intubated: 1 }, { city: 'Aparecida', date: '2021-01-05', totalDeaths: 22, totalCases: 822, totalRecovered: 724, totalBeds: 8, intubated: 3 }, { city: 'Aparecida', date: '2021-01-06', totalDeaths: 22, totalCases: 831, totalRecovered: 724, totalBeds: 11, intubated: 2 }, { city: 'Aparecida', date: '2021-01-07', totalDeaths: 22, totalCases: 847, totalRecovered: 724, totalBeds: 15, intubated: 2 }, { city: 'Aparecida', date: '2021-01-10', totalDeaths: 22, totalCases: 857, totalRecovered: 724, totalBeds: 16, intubated: 4 } ]; const totalDeathsCurve = data.map((item, index) => { if (index === 0) return 0; return data[index].totalDeaths - data[index - 1].totalDeaths }); console.log(totalDeathsCurve);

簡而言之,您 map 您的數據和:

  1. 將第一項的totalDeaths設置為起點 (0)
  2. 從當前項目的totalDeaths中減去上一個項目以獲得每日總數

無論如何,請注意,如果您的數據中缺少天數(並且您有;例如,從 2021-01-07 直接到 2021-01-10 的 go),差異將不代表實際的每日差異; 它僅代表與上一個條目的差異

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM