Python CSV 分组列到混合元素字典列表

Python CSV Grouped Columns to list of dict of mixed elements

我正在为 websphere 编写一个 jython 脚本,它将接受 sys.argv 作为 list of dict 来执行进一步的处理-

我需要帮助将 CSV 数据转换为混合元组列表的字典列表,如下所示-

输入CSV-

cluster_name,pool_name,min,max,inactive_time,description,action
Clst1,WebContainer,25,25,60000,Revisit,modify
Clst3,WebContainer,50,50,60000,revisit,modify
Clst6,WebContainer,50,50,60000,revisit,modify
Clst1,ORB.thread.pool,,,,,delete
Clst3,ORB.thread.pool,,,,,delete`

我正在尝试使用 pandas 对列进行分组但无法创建混合元素字典

需要下面的对象(混合元素的字典列表)

[
 {cluster_name:'Clst1',
  pool_name:[
         (WebContainer,25,25,60000,Revisit,modify),
         (ORB.thread.pool,,,,,delete)]},
 {cluster_name:'Clst3',
  pool_name:[
         (WebContainer,50,50,60000,revisit,modify), 
         (ORB.thread.pool,,,,,delete)]},
 {cluster_name:'Clst6',
  pool_name:[
         (WebContainer,50,50,60000,revisit,modify)
        ]}
]

这样我就可以将此对象用作 jython 脚本的 sys.argv。

尝试:

from io import StringIO
import pandas as pd

csvfile = StringIO("""cluster_name,pool_name,min,max,inactive_time,description,action
Clst1,WebContainer,25,25,60000,Revisit,modify
Clst3,WebContainer,50,50,60000,revisit,modify
Clst6,WebContainer,50,50,60000,revisit,modify
Clst1,ORB.thread.pool,,,,,delete
Clst3,ORB.thread.pool,,,,,delete""")

df = pd.read_csv(csvfile)

s = df.set_index(['cluster_name']).apply(tuple, axis=1).rename('pool_name').groupby(level=0).agg(list).reset_index()

s.to_json(orient='records')

输出:

[{"cluster_name":"Clst1","pool_name":[["WebContainer",25.0,25.0,60000.0,"Revisit","modify"],["ORB.thread.pool",null,null,null,null,"delete"]]},{"cluster_name":"Clst3","pool_name":[["WebContainer",50.0,50.0,60000.0,"revisit","modify"],["ORB.thread.pool",null,null,null,null,"delete"]]},{"cluster_name":"Clst6","pool_name":[["WebContainer",50.0,50.0,60000.0,"revisit","modify"]]}]