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?
Related
this is how the data frame looks I want to group by day and then do the following to get merged intervals for each group.Is there an elegant way to shrink merge overlapping intervals for each day?
(df["startTime"]>df["endTime"].shift()).cumsum()
I know that I can add a column that denotes the partition on day like so
df["partition"]=df.groupby(["actualDay","weekDay"]).ngroup()
but how do I make a shift exclusively within the group?
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()
In my dataset, which is in parquet files,I have different data with set columns. The ones I am interested in are state, ids, and dates. I would like to group the data by state and then count distinct ids per month. However, dates are already in YYYY-MM-DD format, so when I run my query:
df.groupby(["state", "date"])["id"].count()
My result is count for each date separately for each state.
How could I modify it to iterate through months separately without changing the whole data files?
Since you didn't provide dummy data for testing so you can try:
Firstly ensure that your date column is of type datetime:
df['date']=pd.to_datetime(df['date'])
Then:
out=df.groupby(['state',pd.Grouper(key='date',freq='m')])['id'].nunique()
OR
out=df.groupby(['state',df.pop('date').dt.floor('m')])['id'].nunique()
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 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()