import pandas as pd
d = {'A': [1,2,3,4], 'B': [[[1,2],[2,3]],[[3,4],[2,5]],[[5,6],[5,6],[5,6]],[7,8]]}
df = pd.DataFrame(data=d)
C = [1,2,3,4,5,6,7,8]
我有一个pandas数据框,并希望将C列表的每个元素附加到B的每个嵌套列表中,并保持结构,以使结果数据框为:
'A': [1,2,3,4]
'B': [[[1,2,1],[2,3,2]],[[3,4,3],[2,5,4]],[[5,6,5],[5,6,6],[5,6,7]],[7,8,8]]
Mybe有一个更优雅的解决方案,但这可行:-)
for i in d['B']:
for j in i:
if (isinstance(j, list)):
j.append(C.pop(0))
else:
i.append(C.pop(0))
break
基于timgebs评论的更有效的解决方案(谢谢!):
f = iter(C)
for i in d['B']:
for j in i:
if (isinstance(j, list)):
j.append(next(f))
else:
i.append(next(f))
break
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句