K.R
K.R

Reputation: 5

How to using pandas rolling.apply with function for calculate multi columns?

I have a Dataframe with date and id (sorted).

> date              id        newid (expected result)
> 2019-01-01 10:00   1   20190101000001-A
> 2019-01-01 11:00   1   20190101000002-A
> 2019-01-01 12:00   1   20190101000003-A
> 2019-01-01 19:00   2   20190101000001-A
> 2019-01-02 09:00   2   20190102000001-A
> 2019-01-02 10:00   2   20190102000002-A
> 2019-01-05 15:00   3   20190103000001-A

def create_new_id(params):
    if (previous_date != recent_date) or (previous_id != recent_id):
        new_id = 'date000001-A'

    if (previous_date == recent_date) and (previous_id == recent_id):
        new_id = previous_new_id + 1# (change date000001-A to date000002-A)

    return new_id

As an Example data, I want to generate a new id by creating a condition to check previous value.

I try to use by this

df['newid ] = df.rolling(window=2).apply(create_new_id)

but I don't know the correct way to use.

Upvotes: 0

Views: 66

Answers (1)

giser_yugang
giser_yugang

Reputation: 6166

Try

df['newid'] = df['date'].dt.strftime('%Y%m%d')+(df.groupby([df['date'].dt.date,'id']).cumcount()+1).astype(str).str.zfill(6) + '-A'
print(df)

# print
                 date  id             newid
0 2019-01-01 10:00:00   1  20190101000001-A
1 2019-01-01 11:00:00   1  20190101000002-A
2 2019-01-01 12:00:00   1  20190101000003-A
3 2019-01-01 19:00:00   2  20190101000001-A
4 2019-01-02 09:00:00   2  20190102000001-A
5 2019-01-02 10:00:00   2  20190102000002-A
6 2019-01-05 15:00:00   3  20190105000001-A

Upvotes: 1

Related Questions