问题描述
我有这个python脚本,可以读取json文件,挑选出销量最高的汽车(完成这一部分),但是现在我需要弄清楚如何找到我们销量最高的年份(car_year) json文件示例,2002年共售出296辆汽车,而2007年arround则售出264辆汽车,我想出了如何对json文件的所有“ car_sales”进行求和,但我需要找出销量最高的年份
Python脚本:
#!/usr/bin/env python
import json
data = json.load(open('/home/ahmed/events.json'))
#finding the item with the highest sale
event=max(data,key=lambda ev: ev['total_sales'])
print (event)
#sum the "car_sales" of all the items in the json file
count = sum(map(lambda x: int(x['total_sales']),data))
print (count)
这是json文件(一个测试)
[
{
"id": 47,"car": {
"car_make": "Lamborghini","car_model": "Murciélago","car_year": 2002
},"price": "$13724.05","total_sales": 149
},{
"id": 48,"car": {
"car_make": "volvo","car_model": "x20","car_year": 2010
},"total_sales": 10
},{
"id": 49,"car": {
"car_make": "kia","car_model": "kia1.2","car_year": 2007
},"total_sales": 114
},{
"id": 50,"car": {
"car_make": "renault","car_model": "p300","total_sales": 147
},{
"id": 51,"car": {
"car_make": "ferrari","car_model": "red","total_sales": 150
}
]
解决方法
- 使用
import { Component,Input,OnInit } from '@angular/core'; @Component({ selector: 'app-rostericon',template: ` <i *ngIf="!layered" class="fa" [class]="iconClass" [style]="customStyle"></i> <span *ngIf="layered" className="fa-layers fa-fw"> <i class="fa" [class]="layer1"></i> <i class="fa" [class]="layer2" style="transform: shrink-6"></i> </span> `,styleUrls: ['./rostericon.component.scss'] }) export class RostericonComponent implements OnInit { @Input() icon:string; customStyle: any = {}; iconClass = ""; layer1 = ""; layer2 = ""; layered: boolean = false; constructor() { } ngOnInit(): void { switch (icon) { //example of how to handle the case case "copy": customStyle = { fontColor: red }; iconClass = "fa-copy"; break; case "reset": customStyle = { fontColor: red }; iconClass = "fa-undo-alt"; break; case "question": layered = true; layer1 = "fa-square"; layer2 = "fa-question"; break; case ... case ... case ... } } }
- 使用
pandas.DataFrame.sum
获取多个列之一的总和 - 使用Pandas: Boolean Indexing进行矢量化数据选择。
- 使用
- 分解
pandas
-
df['car.car_year'][df.total_sales == df.total_sales.max()]
选择返回的所需列- 对所有列使用
df['car.car_year']
- 对所有列使用
-
df
创建所有行的布尔值,其中[df.total_sales == df.total_sales.max()]
与total_sales
相同
-
- 使用
pandas.DataFrame.groupby
按特定列分组并汇总不同的计算,例如total_sales.max()
和.sum
.max