2016-06-16 78 views
1

從元組列表到數組,第二行成爲將它打印到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") 
] 

母線跳閘設置我的數據,當我打印到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)) 

我得到:

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 

如何將其更改爲此格式?

    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 

回答

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

輸出:

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 

更多有關pandas reshaping and pivot table

+0

般的魅力!謝謝@MaThMaX。 – mongotop

+1

@mongotop,很高興幫助!有關[大熊貓重塑和數據透視表](http://pandas.pydata.org/pandas-docs/stable/reshaping.html) – MaThMaX

+1

的更多信息的確很有幫助!再次感謝你!我添加了你的鏈接到你的答案,很容易找到未來的求職者:) – mongotop

相關問題