我有一个包含以下列的DataFrame:id, jan_x, jan_y, feb_x, feb_y, ..., dec_x, dec_y
,我希望导出为json,其结构如下:
{
"id1": [
[jan_x, feb_x, ..., dec_x],
[jan_y, feb_y, ..., dec_y]
],
"id2": [
[jan_x, feb_x, ..., dec_x],
[jan_y, feb_y, ..., dec_y]
]
}
初始键,例如id1
,对应于我的 Dataframe 的id
列中的一个id。如果没有任何自定义解析函数,是否有一种直接的函数方法来实现这一点?我尝试将其作为json转储,但没有捕获所需的列表结构。
这里是一个样本 Dataframe 只有两个月。
data = {'id': ['1', '2', '3', '4'],
'jan_x': [1, 2, 3, 4],
'jan_y': [5, 6, 7, 8],
'feb_x': [9, 10, 11 12],
'feb_y': [13 14, 15, 16]}
df = pd.DataFrame(data)
样本输出:
{
"1": [
[1, 9],
[5, 13]
],
"2": [
[2, 10],
[6, 14]
],
"3": [
[3, 11],
[7, 15]
],
"4": [
[4, 12],
[8, 16]
]
}
2条答案
按热度按时间js4nwp541#
我不确定您所说的“任何自定义解析函数”是什么意思,但这里是我的尝试。
解决方案使用
iterrows
来遍历行。对于每一行,我使用上面定义的x_columns
变量获取以_x结尾的列,对于以_y结尾的列也是如此。row[x_columns]
将值作为Pandas系列提供给您,因此你需要在添加之前把它转换成一个列表来适应你想要的格式。2我把所有这些都附加到一个结果变量中,并在最后打印这个结果变量。下面是我的示例输入:
下面是输出:
sy5wg1nm2#
更新:
在按通用后缀(“x”,“y”,...)聚合后使用
to_dict('list')
:输出: