I have a db table containing a datetime column with values stretching over 24hours. If I use pandas dataframe groupby function to give a minute by minute aggregation, this will throw everything into 0-59 buckets regardless of which hour they were in.
How do I get minute by minute aggregations spread over the timeframe of the table, in this case 24 hours? Also, for those minutes in which there is no values in the table, how do I insert a zero count for that minute into the dataframe?
Try using pd.TimeGroupper
import pandas as pd
df = pd.DataFrame(index=pd.date_range("11:00", "21:30", freq="100ms"))
df['x'] = 1
g = df.groupby(pd.TimeGrouper('S')).sum()
Related
I have timeseries data that I want to query. The data is collected over multiple sensors. I want to direclty resample the data when loading: So each sensor separately resampled. Using pandas this can be reached like this:
#df is a pandas dataframe. Index is a timestamp (datetime64).
df=df.groupby('group').resample('1H').mean()
In sql i tried an approach like this:
SELECT date_trunc('hour', timestamp) AS timestamp, avg(signal.value) AS value, source_name,
FROM signal AS t_signal
GROUP BY(1, t_source.name)
This gives me different results, since in the first case with pandas, the resampling will create a row with a unique timestamp even if the original data did not have a datapoint within a specific hour.
The date_trunc does only aggregate existing data. is there a function that does the same as pandas resampling?
Creating a SELECT or table with only the timestamps you want (from-to) and then a full-outer-join with your resampled data should work.
Then, you only have to fill the NULL's with what you want to be the missing data.
Does this help?
In my dataset as follows (two columns: DATE and RATE)
I want to get the mean for the RATE for each day (from the dataset, you can see that there are multiple rate values for the same day). I have about 1,000 rows, so that I am trying to find an easier way to calculate the mean for each day, then save the results to a data frame.
You have to group by date then aggregate
https://pandas.pydata.org/docs/reference/api/pandas.core.groupby.DataFrameGroupBy.aggregate.html
In your case
df.groupby('DATE').agg({'RATE': ['mean']})
You can groupby the date and perform mean operation.
new_df = df.groupby('DATE').mean()
My dataframe is presented above. The dtypes are
weekday int64
date datetime64[ns]
time object
customers int64
dtype: object
I'd like to sum the customers column to be the count of customers arrived in the past 2 hours (stored in column date). However, using the Pandas Rolling functionality, I can only write
df['customers'] = df['date'].rolling(2).count()
This only counts the previous two date rows completely disregarding datetime values. I'd like to write
df['customers'] = df['date'].rolling('2H').count() #desired: 2H
to get the correct result. However, I'm getting ValueError: window must be an integer. Reading the rolling documentation from pandas, a datetime object should be able to receive a rolling time window (https://pandas.pydata.org/docs/reference/api/pandas.DataFrame.rolling.html). I'm completely clueless why my datetime column cannot use this functionality.
Create sorted DatetimeIndex:
df['date'] = pd.to_datetime(df['date'])
df = df.set_index('date').sort_index()
df['customers'] = df['customers'].rolling('2H').count()
I can inject timestamp in a dataframe column. But I wanted the timestamp column to be unique value (or increasing in nature, even by millisecond). What I currently have -
from datetime import datetime
from pyspark.sql.functions import lit
df = spark.createDataFrame(["10","11","13"], "string").toDF("age")
df = df.withColumn("ts", lit(datetime.now()))
display(df)
You cannot get a timestamp for each row, that is unique over the DataFrame depending on when Spark processes that row, because the data is distributed, so you’ll never have control over when that row was processed. That being said:
If you want the current timestamp to be added as a column, you’ll get better mileage if you use pyspark.sql.functions.current_timestamp.
If you want a column that provides increasing indices, use pyspark.sql.functions.monotonically_increasing_id().
I have a use case where:
Data is of the form: Col1, Col2, Col3 and Timestamp.
Now, I just want to get the counts of the rows vs Timestamp Bins.
i.e. for every half hour bucket (even the ones which have no correponding rows), I need the counts of how many rows are there.
Timestamps are spread over a one year period, so I can't divide it into 24 buckets.
I have to bin them at 30 minutes interval.
groupby via pd.Grouper
# optionally, if needed
# df['Timestamp'] = pd.to_datetime(df['Timestamp'], errors='coerce')
df.groupby(pd.Grouper(key='Timestamp', freq='30min')).count()
resample
df.set_index('Timestamp').resample('30min').count()