微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

freeCodeCamp 挑战指南:使用 reduce 方法分析数据

如何解决freeCodeCamp 挑战指南:使用 reduce 方法分析数据

我在 freeCodeCamp Use the reduce Method to Analyze Data challenge

我试过了:

import plotly.express as px
import plotly.graph_objects as go
# from plotly.subplots import make_subplots
import plotly as py
import pandas as pd
from plotly import tools

d = {'Mkt_cd': ['Mkt1','Mkt2','Mkt3','Mkt4','Mkt5','Mkt1','Mkt5'],'Category': ['Apple','Orange','Grape','Mango','Apple','Orange'],'CategoryKey': ['Mkt1Apple','Mkt2Orange','Mkt3Grape','Mkt4Mango','Mkt5Orange','Mkt1Mango','Mkt2Apple','Mkt4Apple','Mkt5Orange'],'Current': [15,9,20,10,8,21,18,14],'Goal': [50,35,44,24,14,29,28,19]
     }
dataset  = pd.DataFrame(d)

grouped = dataset.groupby('Category',as_index=False).sum()
data = grouped.to_dict(orient='list')
v_cat = grouped['Category'].tolist()
v_current = grouped['Current']
v_goal = grouped['Goal']

fig = go.figure()

## you have a categorical plot and the units for width are in position axis units
## therefore width = 1 will take up the entire allotted space
## a width value of less than 1 will be the fraction of the allotted space
fig.add_trace(go.Bar(
    x=v_current,y=v_cat,marker_color="#ff0000",orientation='h',width=0.25
    ))

## you can show the right edge of the bar by splitting it into two bars
## with the majority of the bar being transparent (opacity set to 0)
fig.add_trace(go.Bar(
    x=v_goal-1,marker_color="#ffffff",opacity=0,width=0.30,))

fig.add_trace(go.Bar(
    x=[1]*len(v_cat),marker_color="#1f77b4",))

fig.update_layout(barmode='relative')
fig.show()

结果是 NaN,我做错了什么?我必须使用箭头函数,因为标准函数声明产生了意想不到的结果?

感谢帮助

解决方法

我会给你提示。

const res = watchList.filter((d) => d.Director === 'James Cameron').map(x => x.averageRating));

然后是另一个数字映射

 res.map(Number)

现在使用 reduce 来计算数字的平均值。一切都解释了here.

,

你可以试试:

const relevant = watchList.filter(movie => movie.Director === "Christopher Nolan");
const total = relevant.reduce((sum,movie) => sum + Number(movie.imdbRating),0);
const average = total / relevant.length;

或合并最后两行:

const relevant = watchList.filter(movie => movie.Director === "Christopher Nolan");
const average = relevant.reduce((sum,0) / relevant.length;
,
function getRating(watchList){
  // Add your code below this line
  var titles = watchList.filter(function(obj){
return obj.Director === "Christopher Nolan";
});
//message(titles);
var averageRating = titles


.reduce( function(sum,obj){
  return sum = sum + parseFloat(obj.imdbRating);
},0)/titles.length;
  //message(watchList.Director);
   
  // Add your code above this line
  return averageRating;
}

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。