0
$\begingroup$

I need to only select the cases for sensor type == air to be rounded to the nearest 5 seconds but do not how I should use a function to make this happen.

I do have the following lines:

In [1]: import pandas as pd
In [2]: df = pd.DataFrame({'timestamp' : ['2020-04-14 00:00:23', '2020-04-14 00:00:37',
                                      '2020-04-14 00:01:01', '2020-04-14 00:01:05',
                                      '2020-04-14 00:01:19'],
                       'sensor type' : ['sound', 'air', 'sound', 'air', 'sound']})
In [3]: df["timestamp"] = pd.to_datetime(df.timestamp)
In [4]: df["rounded_timestamp"] = df.groupby("sensor type").transform(lambda d: d.dt.round("5s"))

Which results in

In [5]: df
Out[5]:
        timestamp sensor type   rounded_timestamp
0 2020-04-14 00:00:23       sound 2020-04-14 00:00:25
1 2020-04-14 00:00:37         air 2020-04-14 00:00:35
2 2020-04-14 00:01:01       sound 2020-04-14 00:01:00
3 2020-04-14 00:01:05         air 2020-04-14 00:01:05
4 2020-04-14 00:01:19       sound 2020-04-14 00:01:20

Hence, I do have the column with the rounded times. But ONLY for air sensors the time should be rounded, how could I get a column with the rounded timestamps for air sensors and the non-rounded timestamps for the sound sensors?

$\endgroup$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.