将嵌套列表写入CSV(Python)

时间:2018-03-02 17:45:54

标签: python list pandas csv

我有一个如下所示的列表:

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

我只是想把它写成一个csv文件,看起来像这样:

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

我无法解决这个问题。我也无法将列表转换为DataFrame。我尝试应用这里建议的一些代码Writing a Python list of lists to a csv file但没有任何成功。

4 个答案:

答案 0 :(得分:4)

熊猫很方便:

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)

答案 1 :(得分:4)

如果在pandas

s=pd.Series(dict(hello)).reset_index()
s.columns=['keyword 1', 'keyword 2', 'frequency']
s
Out[1012]: 
  keyword 1   keyword 2  frequency
0   adapter      iphone      12233
1   battery  smartphone      88884
2      case      iphone      91524

答案 2 :(得分:2)

您可以使用解包:

import csv
hello = [(('case', 'iphone'), 91524), (('adapter', 'iphone'), 12233), (('battery', 'smartphone'), 88884)]
with open('filename.csv', 'w') as f:
   write = csv.writer(f)
   write.writerows([['keyword 1', 'keyword 2', 'frequency']]+[[a, b, c] for [a, b], c in hello])

答案 3 :(得分:1)

如果您可以使用import pandas as pd hello = [(('case', 'iphone'), 91524), (('adapter', 'iphone'), 12233), (('battery', 'smartphone'), 88884)] df=pd.DataFrame({'keyword1':[i[0][0] for i in hello], 'keyword2':[i[0][1] for i in hello], 'frequency':[i[1] for i in hello]}) df[['keyword1', 'keyword2', 'frequency']].to_csv('test.csv') ,则可以执行以下操作:

libgps