我創建了以下數據框:import pandas as pdd = {'T': [1, 2, 4, 15], 'H': [3, 4, 6, 8]}df = pd.DataFrame(data=d, index=['10.09.2018 13:15:00','10.09.2018 13:30:00', '10.09.2018 14:00:00', '10.09.2018 22:00:00'])df.index = pd.to_datetime(df.index)并得到如下結果。Out[30]: T H2018-10-09 13:15:00 1 32018-10-09 13:30:00 2 42018-10-09 14:00:00 4 62018-10-09 22:00:00 15 8如您所見,在 13:45:00 缺少一個值,在 14:00 和 22:00 之間缺少很多值。有沒有一種方法可以自動查找缺失值,插入帶有缺失時間戳的行和缺失時間的 nan 值?我想實現這個:Out[30]: T H2018-10-09 13:15:00 1 32018-10-09 13:30:00 2 42018-10-09 13:45:00 nan nan2018-10-09 14:00:00 4 62018-10-09 14:15:00 nan nan...2018-10-09 21:45:00 nan nan2018-10-09 22:00:00 15 8
1 回答

qq_遁去的一_1
TA貢獻1725條經驗 獲得超8個贊
您可以使用正確的時間步長創建第二個數據幀作為索引,并將其與原始數據連接起來。以下代碼適用于我的情況
# your code
import pandas as pd
d = {'T': [1, 2, 4, 15], 'H': [3, 4, 6, 8]}
df = pd.DataFrame(data=d, index=['10.09.2018 13:15:00','10.09.2018 13:30:00', '10.09.2018 14:00:00', '10.09.2018 22:00:00'])
df.index = pd.to_datetime(df.index)
# generate second dataframe with needed index
timerange = pd.date_range('10.09.2018 13:15:00', periods=40, freq='15min')
df2 = pd.DataFrame(index=timerange)
# join the original dataframe with the new one
newdf = df.join(df2, how='outer')
添加回答
舉報
0/150
提交
取消