How to create dataframe with increasing timestamp column? - dataframe

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().

Related

Minimum date from a list that is after dates from another list

I have two set of dates, startdate and enddate inside a dataframe
For each startdate, I want to find the smallest enddate that's greater than the startdate.
My minimum example code is below but it is very slow, takes 20 seconds each run. Note in my example the date range is the same so a "shift" is possible here but not in my real data.
is there anyway to speed up the code?
import pandas as pd
dates = pd.DataFrame({'startdate':pd.date_range(start='2000-11-03', end='2021-10-01'),'enddate':pd.date_range(start='2000-11-03', end='2021-10-01')})
dates['mindate_after_startdate']=dates['startdate'].apply(lambda x: min(dates['enddate'][dates['enddate']>x],default=datetime.today().date()))
figured it out using pd.merge_asof and direction='forward' argument.

resampling timeseries data per group in sql

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?

Pandas rolling datetime not accepting datetime offset

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()

Group by state and date with grouping date by months with pandas and parquet files

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()

How to get a continuous minutely aggregate with pandas?

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()