我有一個如下所示的資料集:
import pandas as pd
test = pd.DataFrame({
'date': ['2018-01-03 00:00:00', '2018-01-04 00:00:00', '2018-01-05 00:00:00'],
'coal': [2669.0, np.nan ,2731.0],
'hydro': [222.0, np.nan ,230.0],
'unit': ['Gwh', 'Gwh', 'Gwh'],
})
test['date'] = pd.to_datetime(test['date'])
當我嘗試使用插值方法填充空值時:
for x in test.columns.to_list():
test[x] = test[x].interpolate())
它有錯誤:
Invalid fill method. Expecting pad (ffill) or backfill (bfill). Got linear
當我洗掉
test['date'] = pd.to_datetime(test['date'])
它會作業得很好,所以我不知道為什么會這樣:(
而且,當我使用示例df時它作業正常,但是當我在我自己的資料集上嘗試它時,它沒有錯誤,但空值仍然存在,就像從未使用過的fillna()一樣:(
當我使用下面的代碼時,然后使用 fillna 代碼:
test['date'] = test['date'].astype(object)
它適用于我的樣本,但不適用于我自己的資料集:(我自己的資料集仍然像我從未使用過 fillna 方法一樣
我現在很困惑:(想知道是否有人可以解釋為什么會發生這種情況?我嘗試用谷歌搜索,但沒有結果:(
或者我不知道怎么用谷歌搜索:(
PS如果我在我自己的資料集上嘗試一次填充一列,它作業正常,例如:
test['coal'] = test['coal'].interpolate())
test['hydro'] = test['hydro'].interpolate())
但不是 for 回圈:(
它在我第一次將 dtype 更改為浮動時起作用,所以當它是物件(不是所有物件)時可能有問題?
for x in total_list:
df_all[x] = df_all[x].astype(float)
df_all[x] = df_all[x].interpolate()
無論如何,謝謝大家:)這已經花了我2個小時了:(
uj5u.com熱心網友回復:
您只需要插入給定的列
cols_to_interpolate = ["coal", "hydro"]
test[cols_to_interpolate] = test[cols_to_interpolate].interpolate()
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/428735.html
