如何将数据框列转换为列表列表 json 格式?

How to convert dataframe column into list of lists json format?

我的数据框如下所示,我想使用销售列并将其转换为每个月的 json 个文件作为列表列表。

sales dt
156 2022-01
192 2022-01
147 2022-02
192 2022-02
for date in date_range:
        df.loc[df['dt'] == date]['sales'].to_json(f"{out_path}/sales_{date.replace('-', '_')}.json", orient='values',indent=2)

使用这个,我得到了这种格式的 json 文件:

[
156,
192
]

但是,我想要:

[
 [156],
 [192]
]

我创建了这个作为玩具示例。我想在一个非常大的数据框上实现几个月的数据。谁能指出我如何实现这一目标?谢谢。

我不知道数组中单个值的原因,但这段代码有效:

第一个单元格:

months_sales = []
sales = []

for index, row in df.iterrows():
    if  [row["dt"]] in months_sales:
        index_month = months_sales.index([row["dt"]])
        sales[index_month].append([row["sales"]])
    else:
        months_sales.append([row["dt"]])
        sales.append([  [row["sales"]]  ])

第二个单元格:

for index, month in enumerate(months_sales):
   with open(str(month[0])+'.json', 'w') as f:
     f.write(str(sales[index]))
     files.download(str(month[0])+'.json')

您只需要更改文件的路径(idk what environment/libs 您正在使用)。

结果是一个具有 'dt' 列名称和值的文件。例如:

   [
      [156], 
      [192]
   ]

编辑:* 库:

  import pandas as pd
  from google.colab import files
  import json
  import io

你可以试试:

    df = df.groupby('dt',as_index=False).agg({'sales':list})
    df['sales'] = df['sales'].apply(lambda x: [[e] for e in x])
    df.apply(lambda row: pd.Series(row['sales']).to_json(
             f"{out_path}/sales_{row['dt'].replace('-','_')}.json",
             orient='values',indent=2), axis=1)