我想将csv列表数据导出为垂直(列)而不是行。我搜索了3天,找不到解决我问题的解决方案。我在做什么错了?
[['日期','2016-06','2016-09','2016-12','2017-03','2017-06','2017-09','2017-12' ,“ 2018-03”,“ 2018-06”,“ 2018-09”,“ TTM”],[“收入”,“ 20614”,“ 20453”,“ 24090”,“ 22090”,“ 23317”,“ 24538”,“ 28918”,“ 26819”,“ 30085”,“ 29084”,“ 114906”],[“收入成本”,“ 7979”,“ 7844”,“ 9901”,“ 8060”,“ 8456” ,“ 8278”,“ 11064”,“ 9269”,“ 9742”,“ 9905”,“ 39980”],[“毛利润”,“ 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
答案 0 :(得分:0)
您可以这样做
将熊猫作为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)
答案 1 :(得分:0)
@thecruisy,仍然无法使导出正常工作。将列表转换成字典是有意义的。这是我的代码。
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)