我有两个数据框:
df1
id data
1 abc
2 def
3 ghi
4 jkl
df2
id numbers
1 ['123', '456', '789']
2 ['1', '2']
3 ['3', '567']
当我尝试合并数据并使用以下代码将其转换为json时:
df1 = df1.merge(df2, how = 'left')
df_as_json = df1.to_json(orient='records')
我的输出如下:
[{"id" : 1, "data" : "abc", "numbers" : "['123', '456', '789']"},.....]
我的预期输出是:
[{"id" : 1, "data" : "abc", "numbers" : ['123', '456', '789']},.....]
问题在于数字值未转换为JSON数组,而是将其视为字符串。我错过了什么?我该如何解决这个问题?
PS: df2是通过按以下列表进行分组获得的:
id number
1 123
1 456
1 789
2 1
2 2
df2 = df2.groupby('id')['number'].apply(list).reset_index()
df2.columns = ['id','numbers']