0

I want to export csv list data as vertical (column) instead of row. I searched for 3 days and can't find a solution that resolve my problem. What am I doing wrong?

incomeList_2

[['Date', '2016-06', '2016-09', '2016-12', '2017-03', '2017-06', '2017-09', '2017-12', '2018-03', '2018-06', '2018-09', 'TTM'], ['Revenue', '20614', '20453', '24090', '22090', '23317', '24538', '28918', '26819', '30085', '29084', '114906'], ['Cost of revenue', '7979', '7844', '9901', '8060', '8456', '8278', '11064', '9269', '9742', '9905', '39980'], ['Gross profit', '12635', '12609', '14189', '14030', '14861', '16260', '17854', '17550', '20343', '19179', '74926'], ['EBITDA', '5602', '7578', '9050', '8978', '8543', '11155', '12403', '12042', '13868', '13732', '52045']]

export_Income = "D:\Stocks\MSFT_Income-Statement_Export.csv"

with open(export_Income, "w") as output:
    csv_out = csv.writer(output, lineterminator="\n")
    for row in incomeList_2:
        csv_out.writerow(row)

### Current csv export output ###
Date    2016-06 2016-09 2016-12 2017-03 2017-06 2017-09 2017-12 2018-03 2018-06 2018-09 TTM
Revenue 20614   20453   24090   22090   23317   24538   28918   26819   30085   29084   114906
Cost of revenue 7979    7844    9901    8060    8456    8278    11064   9269    9742    9905    39980

### Desired csv export output ###
Date        Revenue     Cost of revenue
2016-06     20614       7979
2016-09     20453       7844
2016-12     24090       9901
Andy
  • 1
  • 1
  • Looks like you need to [transpose your data](https://stackoverflow.com/questions/6473679/transpose-list-of-lists) and then write the CSV file. – crazyGamer Jan 26 '19 at 05:24

2 Answers2

0

You can do it like this

import pandas as pd

incomeList_2 = [
    ['Date', '2016-06', '2016-09', '2016-12', '2017-03', '2017-06', '2017-09', '2017-12', '2018-03', '2018-06',
     '2018-09', 'TTM'],
    ['Revenue', '20614', '20453', '24090', '22090', '23317', '24538', '28918', '26819', '30085', '29084', '114906'],
    ['Cost of revenue', '7979', '7844', '9901', '8060', '8456', '8278', '11064', '9269', '9742', '9905', '39980'],
    ['Gross profit', '12635', '12609', '14189', '14030', '14861', '16260', '17854', '17550', '20343', '19179', '74926'],
    ['EBITDA', '5602', '7578', '9050', '8978', '8543', '11155', '12403', '12042', '13868', '13732', '52045']]

data_dict = {}

for column in incomeList_2:
    name = column[0]
    val = column[1:]

    data_dict[name] = val

df = pd.DataFrame(data = data_dict)
billydh
  • 975
  • 11
  • 27
0

@thecruisy, It's still cannot get the export to work. Convert List into Dictionary makes sense though. Here is my code.

import pandas as pd
for column in incomeList_2:
    headers = column[0]
    values = column[1:]
    incomeDict[headers] = values

df = pd.DataFrame(data=incomeDict)

with open(export_Income, "w") as csv_file:
    csv_writer = csv.writer(csv_file, lineterminator="\n")
    csv_writer.writerows(df)
Andy
  • 1
  • 1