- c - 在位数组中找到第一个零
- linux - Unix 显示有关匹配两种模式之一的文件的信息
- 正则表达式替换多个文件
- linux - 隐藏来自 xtrace 的命令
我正在寻找一种 Python 技术来从 pandas 数据框中的平面表构建嵌套的 JSON 文件。例如,一个 pandas 数据框表怎么可能是这样的:
teamname member firstname lastname orgname phone mobile
0 1 0 John Doe Anon 916-555-1234
1 1 1 Jane Doe Anon 916-555-4321 916-555-7890
2 2 0 Mickey Moose Moosers 916-555-0000 916-555-1111
3 2 1 Minny Moose Moosers 916-555-2222
被获取并导出为如下所示的 JSON:
{
"teams": [
{
"teamname": "1",
"members": [
{
"firstname": "John",
"lastname": "Doe",
"orgname": "Anon",
"phone": "916-555-1234",
"mobile": "",
},
{
"firstname": "Jane",
"lastname": "Doe",
"orgname": "Anon",
"phone": "916-555-4321",
"mobile": "916-555-7890",
}
]
},
{
"teamname": "2",
"members": [
{
"firstname": "Mickey",
"lastname": "Moose",
"orgname": "Moosers",
"phone": "916-555-0000",
"mobile": "916-555-1111",
},
{
"firstname": "Minny",
"lastname": "Moose",
"orgname": "Moosers",
"phone": "916-555-2222",
"mobile": "",
}
]
}
]
}
我已经尝试通过创建一个字典的字典并转储到 JSON 来做到这一点。这是我当前的代码:
data = pandas.read_excel(inputExcel, sheetname = 'SCAT Teams', encoding = 'utf8')
memberDictTuple = []
for index, row in data.iterrows():
dataRow = row
rowDict = dict(zip(columnList[2:], dataRow[2:]))
teamRowDict = {columnList[0]:int(dataRow[0])}
memberId = tuple(row[1:2])
memberId = memberId[0]
teamName = tuple(row[0:1])
teamName = teamName[0]
memberDict1 = {int(memberId):rowDict}
memberDict2 = {int(teamName):memberDict1}
memberDictTuple.append(memberDict2)
memberDictTuple = tuple(memberDictTuple)
formattedJson = json.dumps(memberDictTuple, indent = 4, sort_keys = True)
print formattedJson
这会产生以下输出。每个项目都嵌套在“teamname”1 或 2 下的正确级别,但如果它们具有相同的 teamname,则记录应嵌套在一起。我该如何解决这个问题,以便团队名称 1 和团队名称 2 中各嵌套 2 条记录?
[
{
"1": {
"0": {
"email": "john.doe@wildlife.net",
"firstname": "John",
"lastname": "Doe",
"mobile": "none",
"orgname": "Anon",
"phone": "916-555-1234"
}
}
},
{
"1": {
"1": {
"email": "jane.doe@wildlife.net",
"firstname": "Jane",
"lastname": "Doe",
"mobile": "916-555-7890",
"orgname": "Anon",
"phone": "916-555-4321"
}
}
},
{
"2": {
"0": {
"email": "mickey.moose@wildlife.net",
"firstname": "Mickey",
"lastname": "Moose",
"mobile": "916-555-1111",
"orgname": "Moosers",
"phone": "916-555-0000"
}
}
},
{
"2": {
"1": {
"email": "minny.moose@wildlife.net",
"firstname": "Minny",
"lastname": "Moose",
"mobile": "none",
"orgname": "Moosers",
"phone": "916-555-2222"
}
}
}
]
最佳答案
这是一个可以创建所需 JSON 格式的解决方案。首先,我按适当的列对数据框进行分组,然后我没有为每个列标题/记录对创建字典(并丢失数据顺序),而是将它们创建为元组列表,然后将列表转换为有序字典。为其他所有内容分组的两列创建了另一个 Ordered Dict。列表和有序字典之间的精确分层对于 JSON 转换产生正确的格式是必要的。另请注意,当转储到 JSON 时,sort_keys 必须设置为 false,否则您所有的 Ordered Dict 将重新排列为字母顺序。
import pandas
import json
from collections import OrderedDict
inputExcel = 'E:\\teams.xlsx'
exportJson = 'E:\\teams.json'
data = pandas.read_excel(inputExcel, sheetname = 'SCAT Teams', encoding = 'utf8')
# This creates a tuple of column headings for later use matching them with column data
cols = []
columnList = list(data[0:])
for col in columnList:
cols.append(str(col))
columnList = tuple(cols)
#This groups the dataframe by the 'teamname' and 'members' columns
grouped = data.groupby(['teamname', 'members']).first()
#This creates a reference to the index level of the groups
groupnames = data.groupby(["teamname", "members"]).grouper.levels
tm = (groupnames[0])
#Create a list to add team records to at the end of the first 'for' loop
teamsList = []
for teamN in tm:
teamN = int(teamN) #added this in to prevent TypeError: 1 is not JSON serializable
tempList = [] #Create an temporary list to add each record to
for index, row in grouped.iterrows():
dataRow = row
if index[0] == teamN: #Select the record in each row of the grouped dataframe if its index matches the team number
#In order to have the JSON records come out in the same order, I had to first create a list of tuples, then convert to and Ordered Dict
rowDict = ([(columnList[2], dataRow[0]), (columnList[3], dataRow[1]), (columnList[4], dataRow[2]), (columnList[5], dataRow[3]), (columnList[6], dataRow[4]), (columnList[7], dataRow[5])])
rowDict = OrderedDict(rowDict)
tempList.append(rowDict)
#Create another Ordered Dict to keep 'teamname' and the list of members from the temporary list sorted
t = ([('teamname', str(teamN)), ('members', tempList)])
t= OrderedDict(t)
#Append the Ordered Dict to the emepty list of teams created earlier
ListX = t
teamsList.append(ListX)
#Create a final dictionary with a single item: the list of teams
teams = {"teams":teamsList}
#Dump to JSON format
formattedJson = json.dumps(teams, indent = 1, sort_keys = False) #sort_keys MUST be set to False, or all dictionaries will be alphebetized
formattedJson = formattedJson.replace("NaN", '"NULL"') #"NaN" is the NULL format in pandas dataframes - must be replaced with "NULL" to be a valid JSON file
print formattedJson
#Export to JSON file
parsed = open(exportJson, "w")
parsed.write(formattedJson)
print"\n\nExport to JSON Complete"
关于python - 如何使用平面数据表中的嵌套记录构建 JSON 文件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37713329/
我有一个对象: [ { TEAMGROUP: "AB", TEAMNAME: "TEAM1", SPRINTS: [ { ID: 1,
颜色模型和颜色空间之间的差异 RGB565 与 RGB888 有何不同任何建议链接 YUV vs RGB vs YCbCr。? 最佳答案 RGB 是一种加法颜色模型,其中红色、绿色和蓝色强度以不同的组
我正在从单个顶点/索引缓冲区绘制一个具有多个网格的完整对象,并且它们具有不同的纹理。因此,我想到将纹理 ID 与顶点一起从顶点着色器传递到片段着色器中的片段。问题是禁用插值。我正在使用 GLSL ve
我有一个包含 40000 个 float 的数组,用于指定 map 上的高度级别。我想在 OpenGL ES 2.0 中创建一个网格/平面,为该网格中的每个顶点分配一个来自该数组的高度值,以便它们创建
我真的很喜欢 IQ 的页面以及有关 SDF 的信息: ( https://www.iquilezles.org/www/articles/distfunctions/distfunctions.htm
我创建了 QPushButton在带有此样式表的 Qt Designer 中: QPushButton#pushButton { background-color: #ffffff; } QP
所以我正在寻找一些平面 map 的解决方法,因为它在 IE 上不起作用,我找到了这个:但我不太明白为什么它会起作用 var gadjets = [ {computers:['asus', 'hp'
child Actor 会不会太多?例如,如果我有一个有 10000 个 child Actor 的 Actor ,与每个有 1000 个 child Actor 的 10 个 Actor 相比,这会
我有一个由法线 (n) 和距离 (d)(距原点)定义的平面。我想把它改造成一个新的系统。 长路是这样的: 1) 将距离 (d) 与法线 (n) 相乘得到一个向量 (p) 2) 旋转 (R) 并平移 (
问题: 从球体中减去立方体会得到一个结果,其中 z 轴保留体积,但 y 轴和 x 轴产生平面圆盘,如图所示。我不确定为什么球体在那些方面正在失去体积。我正在使用 threeCSG 的典型减法。 代码:
我通过 SQL 查询从我们的 ERP 获取产品数据,由此返回的数据在大小级别非常平坦。一个产品有 3 个级别: 风格 颜色 尺寸 一种款式有多种颜色,一种颜色有多种尺码。 我创建了以下模型: publ
我正在尝试展开一些 json 数据。如果我像下面这样使用我的测试数据,一切正常! var data = [ { "title": 1, "parentids": [0] }, { "title
我希望使用 SceneKit 在 Swift 中的 3D 空间中绘制多个平面。具体来说,这些表面都将位于双曲面内。我以前从未绘制过自定义形状/对象,而且在尝试理解文档时我已经迷失了方向。 关于在 3D
预先感谢您阅读我的问题。我对 ARKit 非常陌生,并且已经学习了几个教程,这些教程向我展示了如何使用平面检测以及如何为平面使用不同的纹理。这个功能真的很棒,但这是我的问题。玩家是否可以先将飞机放置在
我正在阅读下面的源代码,我想知道我到底为什么要使用平面图方式。正如我所看到的,与通过 if 语句进行简单的 null 检查相比,实例化了更多的对象,执行了更多代码,这将在第一个 null 时终止,而不
我正在编写一个 Rails 应用程序并使用 Flat UI 进行样式设置。我目前正在将 flatui-rails gem 与 twitter-bootstrap-rails gem 结合使用。一切正常
我在维基百科中找到了射线平面相交代码的解决方案,该解决方案有效,我只是在其中求解线性方程组。 后来我找到了一些点到平面投影的代码,显然实现方式不同,并且在特定条件下也会产生不同的解决方案。 但是,我并
我正在使用 http://designmodo.github.io/Flat-UI/ 中的扁平 UI 我复制了复选框示例页面中的所有文件和代码。 但是我注意到该复选框并未显示为样式复选框,但在我单击初
这个问题已经有答案了: True Isometric Projection with HTML5 Canvas (3 个回答) 已关闭 7 年前。 我想创建一个等轴测图。该 map 存在等距矩形,如图
http://designmodo.github.io/Flat-UI/ 我想创建一个 Css 下拉菜单,我已经完成了下拉部分,但是我似乎无法模拟转换,也不知道如何编写这些代码。这是我目前所知道的,在
我是一名优秀的程序员,十分优秀!