如何在所需索引处的pandas数据框中插入新行

Gur*_*ani 5 python nan resampling dataframe pandas

我有一个缺少日期的数据框

print data 

Date  Longitude  Latitude  Elevation  Max Temperature  \
4/11/1979  83.75  24.197701       238     44.769           20.007   
4/12/1979  83.75  24.197701       238     41.967           18.027   
4/13/1979  83.75  24.197701       238     43.053           20.549    
4/15/1979  83.75  24.197701       238     40.826           20.189
Run Code Online (Sandbox Code Playgroud)

我要如何插入4/14/19794th

打印数据

Date  Longitude  Latitude  Elevation  Max Temperature  \
4/11/1979  83.75  24.197701       238     44.769           20.007   
4/12/1979  83.75  24.197701       238     41.967           18.027   
4/13/1979  83.75  24.197701       238     43.053           20.549
4/14/1979  0.0    0.0             0       0.0              0.0
4/15/1979  83.75  24.197701       238     40.826           20.189
Run Code Online (Sandbox Code Playgroud)

jez*_*ael 4

首先转换列Date to_datetime,然后set_index进行重采样。

您可以使用resampleby D( days) ,然后需要填充NaNto 0,一种可能的解决方案是replace({np.nan:0})

df['Date'] = pd.to_datetime(df.Date)
df.set_index('Date', inplace=True)

df = df.resample('D').replace({np.nan:0}).reset_index()
print (df)
        Date  Longitude   Latitude  Elevation     Max  Temperature
0 1979-04-11      83.75  24.197701      238.0  44.769       20.007
1 1979-04-12      83.75  24.197701      238.0  41.967       18.027
2 1979-04-13      83.75  24.197701      238.0  43.053       20.549
3 1979-04-14       0.00   0.000000        0.0   0.000        0.000
4 1979-04-15      83.75  24.197701      238.0  40.826       20.189
Run Code Online (Sandbox Code Playgroud)