英文:
How to reshape a list of lists into a data frame for csv export
问题
我想将一系列列表叠加到一个数据框中:
我目前有一个包含30个元素的列表,每个元素都有两个子元素。当我将其导出为CSV文件时,我希望这两个子元素分别占据一行。如果我限制为前10行,我可以实现这一点:
但是当我添加新行时,它将这两个子元素合并成一个:
我使用了上面的代码,尝试将它们一起压缩。如何叠加这些并保持第一种配置?
英文:
I want to stack a list of lists on top of each other into a data frame:
I currently have a list that is 30 elements long and each element has two elements in it. When I export it to CSV I want the 2 element to have a row each, I can achieve this if I restrict it to the first 10 rows:
When I add the new rows, it combines the 2 elements into one:
data=pd.DataFrame(data=zip(data[0:10],data[10:20]))
df = pd.DataFrame(data).T.set_axis(headers, axis=1)
df.to_csv('GFG.csv', mode='w', index=False, header=True)
I used the above code, so I just tried to zip them together. How would I stack these and maintain the first configuration?
答案1
得分: -1
好的,我理解了。以下是翻译好的代码部分:
好的,我理解了,所以我假设你的30个元素列表是你的10个标题项连续排列的3个序列。
你可以将这个列表切片成为包含每个序列的10个项的组,并连接为每个组创建的数据框。
df = pd.concat([pd.DataFrame(data=data[i:i+10]).T for i in range(0,len(data),10)], ignore_index=True).set_axis(headers, 1)
英文:
Ok gotya, so I'm assuming your 30 element list is 3 sequences of your 10 header items back to back.
You can slice this list into your 10-item groups and concatenate the dataframes created for each one.
df = pd.concat([pd.DataFrame(data=data[i:i+10]).T for i in range(0,len(data),10)], ignore_index=True).set_axis(headers, 1)
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论