我正在尝试解析一个excel,以便使用xlrd将它与其他数据结合起来。你知道吗
我在网上搜索了一个解决方案,但不管我怎么努力,都无法使它工作。如何用这些数据构建JSON对象?我提供了一个示例,说明了excel中的原始数据是什么样的,以及我希望对象是什么样的。你知道吗
Date User Hours Manager Category
2019-02-25 User1 4 Manager1 Category1
2019-04-01 User2 2 Manager1 Category1
2019-04-01 User2 3 Manager1 Category1
2019-04-01 User2 2 Manager1 Category2
2019-05-06 User3 3 Manager2 Category1
2019-01-07 User4 1 Manager3 Category2
2019-04-07 User2 4 Manager1 Category1
2019-01-21 User4 2 Manager3 Category2
2019-04-07 User2 2 Manager1 Category2
我想要的数据是:
{
Manager1: { User1: {February: {Category1: 4}}
User2: {April: {Category1: 9,
Category2: 4}}
},
*Manager2...*
}
不用“二月”作为一个月的例子,简单的数字就可以了。我现在使用下面的代码将excel日期类型从“43570.0”格式转换为表示月份的数字
excel_date = int(row_values[0])
full_date = datetime.fromordinal(datetime(1900,1,1).toordinal() + excel_date -2)
month = full_date.date().month
我能够逐行解析它,但我不知道如何将它作为一个对象组合在一起。因为在这个数据中有大约15k行,所以我想把upp每个值加上每个人的小时数
object[manager][user][month][category] += hours
但是我不知道我应该如何构建我的对象,因为我只收到关键错误。我试着添加一个defaultdict函数,但我还没能解决这个问题
我现在用这段代码进行解析,但无法理解最后一部分:
for rownum in range(2, file_sh.nrows-1):
row_values = file_sh.row_values(rownum)
excel_date = int(row_values[0])
full_date = datetime.fromordinal(datetime(1900,1,1).toordinal() + excel_date -2)
month = full_date.date().month
manager = row_values[4]
user = row_values[2]
row_type = row_values[5]
hours = row_values[3]
print(month, manager, user, row_type, hours)
returns: 2 Manager1 User1 Category1 4
谢谢。你知道吗
我为pandas、numpy和Python的其他数据科学库购买了Udemy课程。这似乎是一条路要走,即使我还没有经历过这一切,并解决了我最初的问题。你知道吗
用
pandas
怎么样?你知道吗您可以以excel格式读取数据,只提取月份,并使用所需的计算值制作
pivot_table()
:接下来您可以用
orient='index'
导出它:结果:
不完全是post中的格式,但是值在那里(或者对json做一些后处理)。你知道吗
编辑
或者在调用
to_json()
之前将其转换回DataFrame
:结果:
相关问题 更多 >
编程相关推荐