2014-04-19 33 views
0

我試圖從我的熊貓數據框中獲取一些元數據:我想知道有多少行在數據庫的所有表中都有數據。下面的代碼給我:數據庫到數據框和獲取有關填充列的信息

PandasError: DataFrame constructor not properly called! 

但我不知道爲什麼。這似乎博克沒有數據在所有的表,但我不明白爲什麼這應該是問題...

engine = sqlalchemy.create_engine("mysql+mysqldb://root:[email protected]/%s" % db) 
meta = sqlalchemy.MetaData() 
meta.reflect(engine) 
tables = meta.tables.keys() # Fetches all table names 
cnx = engine.raw_connection() # Raw connection is needed. 

df = pd.read_sql('SELECT * FROM offending_table', cnx) 
df = df.applymap(lambda x: np.nan if x == "" else x) # maak van alle "" een NaN 

count = df.count() 

table = pd.DataFrame(count, columns=['CellsWithData']) 
table 

完整的錯誤信息是:

offending_table 
--------------------------------------------------------------------------- 
PandasError        Traceback (most recent call last) 
<ipython-input-367-f33bb79a6773> in <module>() 
    14  count = df.count() 
    15 
---> 16  table = pd.DataFrame(count, columns=['CellsWithData']) 
    17  if len(all_tables) == 0: 
    18   all_tables = table 

/Library/Python/2.7/site-packages/pandas/core/frame.pyc in __init__(self, data, index, columns, dtype, copy) 
    271           copy=False) 
    272    else: 
--> 273     raise PandasError('DataFrame constructor not properly called!') 
    274 
    275   NDFrame.__init__(self, mgr, fastpath=True) 

PandasError: DataFrame constructor not properly called! 

的表給出這個消息包含幾列,其中沒有數據。時生成的DF的樣子:

name   NaN 
principal_id NaN 
diagram_id  NaN 
version  NaN 
definition  NaN 

當我做:

df.count() 

我得到:

0 

那是預期的行爲?

+2

嘗試將您的示例修剪爲實際失敗的代碼。 – joris

+0

你可以在for循環中添加一個'print t',這樣你就可以看到哪個表給出錯誤。然後可以顯示該特定表的'df'和'count'輸出是什麼? – joris

+0

你確定這是表嗎?因爲那確實很奇怪。順便說一句,如果你給DataFrame一個標量,你會得到這樣的錯誤,比如'pd.DataFrame(5,columns = ['CellsWithData']'。作爲進一步的調試步驟,可能在DataFrame調用之前做一個「print count」 – joris

回答

1

看來,applymap是罪魁禍首這裏:-)

當你有一個空的結果集read_sql查詢了,你會得到一個空的數據幀。例如:

In [2]: df = pd.DataFrame(columns=list('ABC')) 

In [3]: df 
Out[3]: 
Empty DataFrame 
Columns: [A, B, C] 
Index: [] 

利用這個空數據幀,當你再呼籲這個applymap,它apparantly轉換爲一個系列,然後計數只是給出一個數字:

In [10]: df2 = df.applymap(lambda x: np.nan if x == "" else x) 

In [11]: df2 
Out[11]: 
A NaN 
B NaN 
C NaN 
dtype: float64 

In [12]: df2.count() 
Out[12]: 0 

,而這樣做的直接對空數據框算,得到所需的輸出:

In [13]: df.count() 
Out[13]: 
A 0 
B 0 
C 0 
dtype: int64 

我不知道到底是爲什麼applymap做到這一點(或者如果它是一個錯誤),但現在一個簡單的解決辦法是剛做的QUIC如果applymap前K:

if not len(df): 
    df = df.applymap(lambda x: np.nan if x == "" else x) 

其理由是,上述是一個問題,就是DataFrame構造不接受一個標量作爲輸入數據。

相關問題