Note that there are some explanatory texts on larger screens.

plurals
  1. POCompute the nth day from the first event in Pandas
    primarykey
    data
    text
    <p>I have the following data frame, subsetted from my original data frame, with columns <em>event</em>, <em>unixtime</em>, and <em>day</em>, and I want to add another column <em>arbday</em> which is the nth day since the first event (with the first visit being day 1): </p> <pre><code>import numpy as np import datetime as dt &gt;&gt;&gt; testdf = pd.DataFrame({'event': range(1,4), 'unixtime': [1346617885925, 1346961625305,1347214217566]},index=[343352,343353,343354]) &gt;&gt;&gt; testdf['day'] = testdf['unixtime'].apply(lambda x: dt.datetime.utcfromtimestamp(x/1000).date()) event unixtime day arbday 343352 1 1346617885925 2012-09-02 1 343353 2 1346961625305 2012-09-06 5 343354 3 1347214217566 2012-09-09 8 </code></pre> <p>After looking around, I tried to do this by: </p> <pre><code>&gt;&gt;&gt; testdf2['arbday'] = np.where(testdf2['event']==1, 1, testdf2.day.apply(lambda x: x-x[:1])) event unixtime day arbday 343352 1 1346617885925 2012-09-02 1 343353 2 1346961625305 2012-09-06 NaN 343354 3 1347214217566 2012-09-09 NaN or &gt;&gt;&gt; testdf2['arbday'] = np.where(testdf2['event']==1, 1, testdf2.day.apply(lambda x: dt.timedelta(x-x[:1]))) TypeError: 'datetime.date' object is not subscriptable </code></pre> <p>What is the correct way to do this? Any pointer is much appreciated! </p> <p><strong>EDIT</strong>: A follow-up question regarding to applying this over groups is <a href="https://stackoverflow.com/questions/13175251/compute-the-nth-day-from-the-first-event-within-each-group-in-pandas">here</a>.</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload