Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/278.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 如何将数据框列中的嵌套列表垂直拆分为单独的行_Python_Pandas_Dataframe_Nested - Fatal编程技术网

Python 如何将数据框列中的嵌套列表垂直拆分为单独的行

Python 如何将数据框列中的嵌套列表垂直拆分为单独的行,python,pandas,dataframe,nested,Python,Pandas,Dataframe,Nested,我有一个数据帧,我想拆分Co2行: Co1 Co2 1 [{'link':'http:abc.com'},{'link':'http:def.com'}] 2 [{'link':'http:ghi.com'},{'link':'http:lmn.com'}] 预期产量 Co1 Co2 1 http:abc.com 1 http:def.com 2 http:ghi.com 2 http:lmn.com 与列表理解中创建的DataFrame的Diciary一起使用,并与原始数据连接,用于提取列

我有一个数据帧,我想拆分Co2行:

Co1 Co2
1 [{'link':'http:abc.com'},{'link':'http:def.com'}]
2 [{'link':'http:ghi.com'},{'link':'http:lmn.com'}]
预期产量

Co1 Co2
1 http:abc.com
1 http:def.com
2 http:ghi.com
2 http:lmn.com
与列表理解中创建的DataFrame的Diciary一起使用,并与原始数据连接,用于提取列:

import ast

#if values are string repr of lists
dfs = {k:pd.DataFrame(ast.literal_eval(x)) for k, x in df.pop('Co2').items()}
#if values are lists of dicts
#dfs = {k:pd.DataFrame(x) for k, x in df.pop('Co2').items()}

df = df.join(pd.concat(dfs).reset_index(level=1, drop=True)).reset_index(drop=True)
print (df)
   Co1          link
0    1  http:abc.com
1    1  http:def.com
2    2  http:ghi.com
3    2  http:lmn.com
与列表理解中创建的DataFrame的Diciary一起使用,并与原始数据连接,用于提取列:

import ast

#if values are string repr of lists
dfs = {k:pd.DataFrame(ast.literal_eval(x)) for k, x in df.pop('Co2').items()}
#if values are lists of dicts
#dfs = {k:pd.DataFrame(x) for k, x in df.pop('Co2').items()}

df = df.join(pd.concat(dfs).reset_index(level=1, drop=True)).reset_index(drop=True)
print (df)
   Co1          link
0    1  http:abc.com
1    1  http:def.com
2    2  http:ghi.com
3    2  http:lmn.com
和的另一种方式:

和的另一种方式:

print(out) 

   Co1           Co2
0    1  http:abc.com
1    1  http:def.com
2    2  http:ghi.com
3    2  http:lmn.com