2017-08-30 93 views
2

我從一個url中提取了JSON數據。結果是一本字典。如何轉換此字典以便每個鍵都是列,並且時間戳是每行的索引 - 每次調用url時字典values對應於行條目?將json字典轉換爲熊貓行df

下面是數據:

with urllib.request.urlopen('https://api.blockchain.info/stats') as url: 
    block_data = json.loads(url.read().decode()) 

# Convert to Pandas 
block_df = pd.DataFrame(block_data) 

我想:

block_df = pd.DataFrame(block_data) 
block_df = pd.DataFrame(block_data, index = 'timestamp') 
block_df = pd.DataFrame.from_dict(block_data) 
block_df = pd.DataFrame.from_dict(block_data, orient = 'columns') 

但所有嘗試給不同的錯誤:

ValueError: If using all scalar values, you must pass an index

TypeError: Index(...) must be called with a collection of some kind, 'timestamp' was passed

回答

1

裹在列表

pd.DataFrame([block_data]).set_index('timestamp') 

       blocks_size difficulty estimated_btc_sent estimated_transaction_volume_usd  hash_rate market_price_usd miners_revenue_btc miners_revenue_usd minutes_between_blocks n_blocks_mined n_blocks_total n_btc_mined n_tx nextretarget total_btc_sent total_fees_btc   totalbc trade_volume_btc trade_volume_usd 
timestamp                                                                                     
1504121943000 167692649 888171856257  24674767461479      1.130867e+09 7.505715e+09   4583.09    2540   11645247.85     7.92    170   482689 212500000000 281222  483839 174598204968248  41591624963 1653361250000000   43508.93  1.994054e+08 

隨着datetime指數block_data

df = pd.DataFrame([block_data]).set_index('timestamp') 
df.index = pd.to_datetime(df.index, unit='ms') 
df 

        blocks_size difficulty estimated_btc_sent estimated_transaction_volume_usd  hash_rate market_price_usd miners_revenue_btc miners_revenue_usd minutes_between_blocks n_blocks_mined n_blocks_total n_btc_mined n_tx nextretarget total_btc_sent total_fees_btc   totalbc trade_volume_btc trade_volume_usd 
timestamp                                                                                      
2017-08-30 19:39:03 167692649 888171856257  24674767461479      1.130867e+09 7.505715e+09   4583.09    2540   11645247.85     7.92    170   482689 212500000000 281222  483839 174598204968248  41591624963 1653361250000000   43508.93  1.994054e+08 
+0

謝謝,這太棒了。還有一個問題 - 如何在設置後將unix timstamp索引轉換爲datetime? – zsad512

+0

我已更新我的帖子。 – piRSquared