Python:在数据框中填写缺少的日期时间值并填写?

asw*_*a09 4 python dataframe pandas

假设我有一个数据帧:

|       timestamp     | value |
| ------------------- | ----- |
| 01/01/2013 00:00:00 |  2.1  |
| 01/01/2013 00:00:03 |  3.7  |
| 01/01/2013 00:00:05 |  2.4  |
Run Code Online (Sandbox Code Playgroud)

我想将数据框设为:

|       timestamp     | value |
| ------------------- | ----- |
| 01/01/2013 00:00:00 |  2.1  |
| 01/01/2013 00:00:01 |  2.1  |
| 01/01/2013 00:00:02 |  2.1  |
| 01/01/2013 00:00:03 |  3.7  |
| 01/01/2013 00:00:04 |  3.7  |
| 01/01/2013 00:00:05 |  2.4  |
Run Code Online (Sandbox Code Playgroud)

我该怎么做?

jez*_*ael 8

你可以用resampleffill:

print (df.dtypes)
timestamp     object
value        float64
dtype: object

df['timestamp'] = pd.to_datetime(df['timestamp'])

print (df.dtypes)
timestamp    datetime64[ns]
value               float64
dtype: object

df = df.set_index('timestamp').resample('S').ffill()
print (df)
                     value
timestamp                 
2013-01-01 00:00:00    2.1
2013-01-01 00:00:01    2.1
2013-01-01 00:00:02    2.1
2013-01-01 00:00:03    3.7
2013-01-01 00:00:04    3.7
2013-01-01 00:00:05    2.4
Run Code Online (Sandbox Code Playgroud)
df = df.set_index('timestamp').resample('S').ffill().reset_index()
print (df)
            timestamp  value
0 2013-01-01 00:00:00    2.1
1 2013-01-01 00:00:01    2.1
2 2013-01-01 00:00:02    2.1
3 2013-01-01 00:00:03    3.7
4 2013-01-01 00:00:04    3.7
5 2013-01-01 00:00:05    2.4
Run Code Online (Sandbox Code Playgroud)