将嵌套列表写入CSV(Python) [英] Writing a nested list into CSV (Python)

查看:78
本文介绍了将嵌套列表写入CSV(Python)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个看起来像这样的列表:

I have a list that looks like this:

hello = [(('case', 'iphone'), 91524), (('adapter', 'iphone'), 12233), (('battery', 'smartphone'), 88884)]

我只是想将其写入csv文件,如下所示:

And I am simply trying to write it to a csv file, looking like this:

keyword 1           keyword 2          frequency
case                iphone             91524
adapter             iphone             12233
battery             smartphone         88884

我想不通.我也无法将列表转换为DataFrame.我尝试应用此处建议的一些代码编写Python列表到csv文件的列表,但没有成功.

I can't figure my way around it. I couldn't transform the list into a DataFrame, either. I tried to apply some code suggested here Writing a Python list of lists to a csv file without any success.

推荐答案

熊猫对此很方便:

import pandas as pd

hello = [(('case', 'iphone'), 91524), (('adapter', 'iphone'), 12233), (('battery', 'smartphone'), 88884)]

df = pd.DataFrame([[i[0][0], i[0][1], i[1]] for i in hello],
                  columns=['keyword 1', 'keyword 2', 'frequency'])

#   keyword 1   keyword 2  frequency
# 0      case      iphone      91524
# 1   adapter      iphone      12233
# 2   battery  smartphone      88884

df.to_csv('file.csv', index=False)

这篇关于将嵌套列表写入CSV(Python)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆