[英]Iterating and Writing Pandas Dataframe NaNs back to MySQL
我試圖將回歸的結果寫回MySQL,但是在迭代擬合值並使NaN寫為空值時遇到問題。 最初,我這樣做了迭代:
for i in dataframe:
cur = cnx.cursor()
query = ("UPDATE Regression_Data.Input SET FITTEDVALUES="+(dataframe['yhat'].__str__())+" where timecount="+(datafrane['timecount'].__str__())+";")
cur.execute(query)
cnx.commit()
cur.close()
.....哪位SQL回復我說:
"mysql.connector.errors.ProgrammingError: 1064 (42000): You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'NaN'
所以,我一直試圖過濾掉NaN,只要求Python在不等於NaN時提交:
for i in dataframe:
if cleandf['yhat']>(-1000):
cur = cnx.cursor()
query = ("UPDATE Regression_Data.Input SET FITTEDVALUES="+(dataframe['yhat'].__str__())+" where timecount="+(datafrane['timecount'].__str__())+";")
cur.execute(query)
cnx.commit()
cur.close()
但后來我明白了:
ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()
所以,我嘗試用以上語法解決這個問題:
if cleandf['yhat'][i]>(-1000):
但是得到這個:
ValueError: Can only tuple-index with a MultiIndex
然后嘗試將itterows()添加到兩者中,如下所示:
for i in dataframe.iterrows():
if cleandf['yhat'][i]>(-1000):
但得到與上面相同的問題。
我不確定我在這里做錯了什么,但是假設它是在Pandas DataFrames中迭代的東西。 但是,即使我得到了正確的迭代,我也想把Nulls寫入到NaN出現的SQL中。
那么,您認為我應該怎么做?
我沒有完整的答案,但也許我有一些可能有用的提示。 我相信您將dataframe
視為類似於SQL記錄集的對象。
for i in dataframe
這將迭代數據框中的列名字符串。 i
將采用列名,而不是行。
dataframe['yhat']
這將返回整個列( pandas.Series
,這是一個numpy.ndarray
),而不是單個值。 因此:
dataframe['yhat'].__str__()
將給出一個對人類有用的整個列的字符串表示。 它當然不是可以轉換為查詢字符串的單個值。
if cleandf['yhat']>(-1000)
這會產生錯誤,因為同樣, cleandf['yhat']
是一整個值數組,而不僅僅是一個值。 可以將其視為整列,而不是單行的值。
if cleandf['yhat'][i]>(-1000):
這越來越近,但你真的希望i
在這里是一個整數,而不是另一個列名。
for i in dataframe.iterrows():
if cleandf['yhat'][i]>(-1000):
使用iterrows
似乎對你來說是正確的。 但是, i
接受每行的值,而不是可以索引到列的整數( cleandf['yhat']
是一個完整的列)。
另外,請注意,pandas有更好的方法來檢查缺失值,而不是依賴於一個巨大的負數。 嘗試這樣的事情:
non_missing_index = pandas.isnull(dataframe['yhat'])
cleandf = dataframe[non_missing_index]
for row in cleandf.iterrows():
row_index, row_values = row
query = ("UPDATE Regression_Data.Input SET FITTEDVALUES="+(row_values['yhat'].__str__())+" where timecount="+(row_values['timecount'].__str__())+";")
execute_my_query(query)
我希望你能比我更好地實現execute_my_query
。 但是,這個解決方案並不是你想要的。 您真的想迭代所有行並執行兩種類型的插入。 嘗試這個:
for row in dataframe.iterrows():
row_index, row_values = row
if pandas.isnull(row_values['yhat']):
pass # populate the 'null' insert query here
else:
query = ("UPDATE Regression_Data.Input SET FITTEDVALUES="+(row_values['yhat'].__str__())+" where timecount="+(row_values['timecount'].__str__())+";")
execute_my_query(query)
希望能幫助到你。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.