简体   繁体   中英

Writing a nested list into CSV (Python)

I have a list that looks like this:

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

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

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.

Pandas is convenient for this:

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)

If in 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

You can use unpacking:

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])

If you're OK with using pandas , you can do the following:

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')

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM