2015-06-23 40 views
0

,創建一個空的數據幀大熊貓:附加熊貓數據幀時2個索引

results = pd.DataFrame(columns=['age','timestamp','score']).set_index(['age', 'timestamp']) 

更DataFrames將被附加到初始results數據幀。

result = pd.DataFrame({'age': age, 
          'timestamp': timestamp, 
          'score': score 
          }).set_index(['age', 'timestamp']) 

    # error then occurs at this point 

    results.append(result) 

,我們得到的錯誤

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

請告訴我追加第二數據框的正確方法?

+0

你的問題是要傳遞一個字典,當你通過的值需要可迭代的數據字典,所以NP陣列或列表或系列 – EdChum

+0

如果你不需要'results'爲一個'DataFrame'直到所有的附加操作完成,那麼收集元組列表中的所有數據會更快,然後一次構建DataFrame:'result = pd.DataFrame(results,columns = [.. 。])。set_index([...])'。 – unutbu

回答

0

試試這個。由於您新添加的記錄只有一行。通過新的數據幀初始化會引入開銷。只需將字典通過.loc傳遞給當前的DF即可。

請注意,逐個添加記錄不是性能高效的。但是,如果這是你的代碼邏輯的一部分,這是不可避免的,那麼.loc會給你的表現遠遠好於pd.append()pd.concat()

import pandas as pd 
import numpy as np 
import datetime as dt 

# create an empty df 
results = pd.DataFrame(columns=['age', 'timestamp', 'score']) 
Out[71]: 
Empty DataFrame 
Columns: [age, timestamp, score] 
Index: [] 

# write new record in dict, make sure the keys match df column names 
new_record = {'age': 23, 'timestamp': dt.datetime(2015,1,1), 'score':98} 
# use .loc to enlarge the current df 
results.loc[len(results)] = new_record 

Out[73]: 
    age timestamp score 
0 23 2015-01-01  98