简体   繁体   中英

Re-sample df to microsecond - Pandas

I am trying to re-sample timestamps in a df to display every 0.1 seconds. It is re-sampling but I'm losing the data relative to those timestamps.

d = ({   
    'Time' : ['2010-07-27 09:25:31.1','2010-07-27 09:25:31.2','2010-07-27 09:25:31.4','2010-07-27 09:25:31.5','2010-07-27 09:25:31.6','2010-07-27 09:25:31.9','2010-07-27 09:25:32.0'],
    'Area' : ['A','A','A','A','A','A','A',],
   })

df = pd.DataFrame(data=d)

df = df.set_index('Time').asfreq('0.1S').reset_index()

Out:

                     Time Area
0 2010-07-27 09:25:31.100  NaN
1 2010-07-27 09:25:31.200  NaN
2 2010-07-27 09:25:31.300  NaN
3 2010-07-27 09:25:31.400  NaN
4 2010-07-27 09:25:31.500  NaN
5 2010-07-27 09:25:31.600  NaN
6 2010-07-27 09:25:31.700  NaN
7 2010-07-27 09:25:31.800  NaN
8 2010-07-27 09:25:31.900  NaN
9 2010-07-27 09:25:32.000  NaN

Intended:

0 2010-07-27 09:25:31.100  A
1 2010-07-27 09:25:31.200  A
2 2010-07-27 09:25:31.300  NaN
3 2010-07-27 09:25:31.400  A
4 2010-07-27 09:25:31.500  A
5 2010-07-27 09:25:31.600  A
6 2010-07-27 09:25:31.700  Nan
7 2010-07-27 09:25:31.800  NaN
8 2010-07-27 09:25:31.900  A
9 2010-07-27 09:25:32.000  A

You can do as follows. First you need to make sure your column is in datetime64[ns] & then use resample on that column

df['Time']=pd.to_datetime(df['Time'])
df.set_index('Time').resample('0.1S').last().fillna(0).reset_index()

Output

                       Time     Area
0   2010-07-27 09:25:31.100     A
1   2010-07-27 09:25:31.200     A
2   2010-07-27 09:25:31.300     0
3   2010-07-27 09:25:31.400     A
4   2010-07-27 09:25:31.500     A
5   2010-07-27 09:25:31.600     A
6   2010-07-27 09:25:31.700     0
7   2010-07-27 09:25:31.800     0
8   2010-07-27 09:25:31.900     A
9   2010-07-27 09:25:32.000     A

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM