我有一个多维列表,其中第一项是日期,第二项是需要添加在一起的日期时间对象。例如(为简单起见,将第二个保留为整数):
[[01/01/2019, 10], [01/01/2019, 3], [02/01/2019, 4], [03/01/2019, 2]]
结果数组应为:
[[01/01/2019, 13], [02/01/2019, 4], [03/01/2019, 2]]
有人这样做的捷径吗?
这种情况的背景是车辆跟踪,我有一个由车辆执行的旅行的清单,我想按天汇总并计算每天的总行驶时间。
答案 0 :(得分:2)
import pandas as pd
# create dataframe out of the given imput
df = pd.DataFrame(data=[['01/01/2019', 10], ['01/01/2019', 3], ['02/01/2019', 4]], columns=['date', 'trip_len'])
# groupby date and sum values for each day
df = df.groupby('date').sum().reset_index()
# output result as list of lists
result = df.values.tolist()
答案 1 :(得分:2)
您应该将数据01/01/2019更改为“ 01/01/2019”。
@naivepredictor建议使用很好的示例,如果您不想导入熊猫,请使用它。
my_list = [['01/01/2019', 10], ['01/01/2019', 3], ['02/01/2019', 4], ['03/01/2019', 2]]
result_d = {}
for i in my_list:
result_d[i[0]] = result_d.get(i[0], 0) + i[1]
print(result_d) #{'01/01/2019': 13, '02/01/2019': 4, '03/01/2019': 2}
print([list(d) for d in result_d.items()]) #[['01/01/2019', 13], ['02/01/2019', 4], ['03/01/2019', 2]]