0

My dataframe head() looks like this:

                                         followers  following
experience   userid date                                     
Intermediate 0      2010-01-02 05:28:38      84330       1331
                    2010-01-02 18:46:36      84330       1331
                    2010-01-02 18:47:22      84330       1331
                    2010-01-02 18:50:12      84330       1331
                    2010-01-02 23:08:55      84330       1331

Where I have more rows. For each userid, I'd like to subtract the first followers value (e.g., in example above, subtract 84330 from all dates in userid=0). Is there some apply() command that will do this?

2
  • What do you mean by subtract? You mean remove the rows or subtract 84330 from a datetime which doesn't make sense to me Commented Oct 2, 2015 at 20:15
  • @EdChum: I mean subtract 84330 from the followers. Meaning for the rows shown above, make those followers 0. However future rows may have more, so their value will be their current value minus 84330. Commented Oct 3, 2015 at 16:54

1 Answer 1

1

find the first row for each userid:

cut = df.groupby('userid').first()

Then merge it back to the original table:

cut.columns = cut.columns.map(lambda x: str(x) + '_a')
df2 = df.merge(cut, left_on=['userid'], right_index=True, how='left')

Then remove these rows that match the first rows value

new = df2[df2['followers'] != df2['followers']][['userid','date','followers']]
Sign up to request clarification or add additional context in comments.

2 Comments

This is close to what I want to do. Please see my comment to EdChum above
You can replace the last line with: df2["diff"] = df2["followers"] - df2["followers_a"] Which will add a new column with the subtract between both values

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.