2017-06-06 148 views
1

我試圖將元組列表轉換爲熊貓數據幀,但無法弄清楚如何實現。我的地址的結構如下所示:將元組列表轉換爲熊貓數據幀

addresses = [ 
[('the vicars inn', 'house'), ('68', 'house_number'), ('church lane', 'road'), ('arlesey', 'city'), ('beds', 'house')], 
[('the old oak', 'house'), ('85', 'house_number'), ('church lane', 'road'), ('arlesey', 'city'), ('beds', 'house')], 
[('adj', 'road'), ('85', 'house_number'), ('high street', 'road'), ('arlesey', 'city'), ('beds', 'house')], 
[('arlesey community centre', 'house'), ('high street', 'road'), ('arlesey', 'city'), ('beds', 'house')], 
[('arlesey community centre', 'house'), ('high street', 'road'), ('arlesey', 'city'), ('beds', 'house')] 
] 

理想情況下,我需要回到像一個數據幀:

 city   house    house_number  road 
0  arlesey  the vicars inn 68     church lane 
1  arlesey  the old oak  85     church lane 

我已經試過到目前爲止轉動表,但它不產生預期結果:

pd.DataFrame.from_records(addresses[0]).pivot(columns=1, values=0) 

有沒有人有任何指導方法,我應該看看實現我理想的數據框?

山姆

+0

看來你在每個記錄兩套房子。你想保留哪一個? – Psidom

回答

2

您可以將每個記錄轉換爲字典,然後使用DataFrame.from_records

pd.DataFrame.from_records([{k: v for v, k in row} for row in addresses]) 

#  city house house_number road 
#0 arlesey beds    68 church lane 
#1 arlesey beds    85 church lane 
#2 arlesey beds    85 high street 
#3 arlesey beds    NaN high street 
#4 arlesey beds    NaN high street