从元组列表到第二行的数组成为标题

mon*_*top 1 python csv arrays list matrix

从元组列表到第二行的数组成为将其打印到csv文件的标题.

这是我在城市原始列表之间的巴士旅行的数据集

L= [ 
("Seattle WA US","Seattle WA US","56"),
("Seattle WA US","North Bend WA US","1"),
("Seattle WA US","Candelaria 137 PR","2"),
("Seattle WA US","La Cienega NM US","2"),
("Seattle WA US","Thousand Palms CA US","1"),
("Oakhurst CA US","Thousand Palms CA US","10")
]
Run Code Online (Sandbox Code Playgroud)

当我打印到csv我得到使用:

ifile  = open('test.csv', "rb")
reader = csv.reader(ifile)
ofile  = open('ttest.csv', "wb")
writer = csv.writer(ofile, delimiter='  ', quotechar='"', quoting=csv.QUOTE_ALL)
writer.writerow(["departure","destination", "trips_count"])
for row in L:
    writer.writerow(list(row))
Run Code Online (Sandbox Code Playgroud)

我明白了:

departure       destination             trips_count
Seattle WA US   Seattle WA US           56
Seattle WA US   North Bend WA US        1
Seattle WA US   Candelaria 137 PR       2
Seattle WA US   La Cienega NM US        2
Seattle WA US   Thousand Palms CA US    1
Oakhurst CA US  Thousand Palms CA US    10
Run Code Online (Sandbox Code Playgroud)

如何将其更改为此格式?

                    Seattle WA US   North Bend WA US    Candelaria 137 PR   La Cienega NM US    Thousand Palms CA US
Seattle WA US       56              1                   2                   2                   1
Oakhurst CA US      0               0                   0                   0                   10
Run Code Online (Sandbox Code Playgroud)

MaT*_*MaX 5

import pandas as pd

L= [ 
("Seattle WA US","Seattle WA US","56"),
("Seattle WA US","North Bend WA US","1"),
("Seattle WA US","Candelaria 137 PR","2"),
("Seattle WA US","La Cienega NM US","2"),
("Seattle WA US","Thousand Palms CA US","1"),
("Oakhurst CA US","Thousand Palms CA US","2")
]

df = pd.DataFrame(L, columns=['departure', 'destination', 'trips_count'])
df = df.pivot(index='departure', columns='destination').fillna(0)
df.to_csv('test.csv')
Run Code Online (Sandbox Code Playgroud)

输出:

In [17]: df = df.pivot(index='departure', columns='destination').fillna(0)

In [18]: df
Out[18]: 
                     trips_count                                    \
destination    Candelaria 137 PR La Cienega NM US North Bend WA US   
departure                                                            
Oakhurst CA US                 0                0                0   
Seattle WA US                  2                2                1   


destination    Seattle WA US Thousand Palms CA US  
departure                                          
Oakhurst CA US             0                    2  
Seattle WA US             56                    1  
Run Code Online (Sandbox Code Playgroud)

有关pandas整形和数据透视表的更多信息