将格式为 Pandas DataFrame 的字符串转换为实际的 DataFrame

Convert string formatted as Pandas DataFrame into an actual DataFrame

我正在尝试将格式化字符串转换为 pandas 数据框。

[['CD_012','JM_022','PT_011','CD_012','JM_022','ST_049','MB_021','MB_021','CB_003'
,'FG_031','PC_004'],['NL_003','AM_006','MB_021'],
['JA_012','MB_021','MB_021','MB_021'],['JU_006'],
['FG_002','FG_002','CK_055','ST_049','NM_004','CD_012','OP_002','FG_002','FG_031',
'TG_005','SP_014'],['FG_002','FG_031'],['MD_010'],
['JA_012','MB_021','NL_003','MZ_020','MB_021'],['MB_021'],['PC_004'],
['MB_021','MB_021'],['AM_006','NM_004','TB_006','MB_021']]

我正在尝试使用 pandas.DataFrame 方法来执行此操作,但结果是整个字符串都放在 DataFrame 中的一个元素内。

你是这个意思吗?

import pandas as pd


list_of_lists = [['CD_012','JM_022','PT_011','CD_012','JM_022','ST_049','MB_021','MB_021','CB_003'
                ,'FG_031','PC_004'],['NL_003','AM_006','MB_021'],
                ['JA_012','MB_021','MB_021','MB_021'],['JU_006'],
                ['FG_002','FG_002','CK_055','ST_049','NM_004','CD_012','OP_002','FG_002','FG_031',
                'TG_005','SP_014'],['FG_002','FG_031'],['MD_010'],
                ['JA_012','MB_021','NL_003','MZ_020','MB_021'],['MB_021'],['PC_004'],
                ['MB_021','MB_021'],['AM_006','NM_004','TB_006','MB_021']]


result = pd.DataFrame({'result': list_of_lists})

最好的方法是用 '],[' 分隔符拆分字符串,然后转换为 df。


import numpy as np
import pandas as pd

def stringToDF(s):
    array = s.split('],[')

    # Adjust the constructor parameters based on your string
    df = pd.DataFrame(data=array,    
              #index=array[1:,0],    
             #columns=array[0,1:]
             ) 

    print(df)
    return df

stringToDF(s)

祝你好运!