0

I have this Dataframe: Dataframe

I would like to copy the value of the Date column to the New_Date column, but not only to the same exact row, I want to every row that has the same User_ID value.

So, it will be: like this!

I tried groupby and then copy, but groupby made all values become lists and other columns with same user_id can have different values in different rows and then it messes up many things.

I tried also:

df['New_Date'] = df.apply(lambda x: x['Date'] if x['User_ID'] == x['User_ID'] else x['New_Date'], axis=1)

But it only copied values to the same row and left the other two empty.

And this:

if (df['User_ID'] == df['User_ID']):
    df['New_Date'] = np.where(df['New_Date'] == '', df['Date'], df['New_Date'])

None accomplished my intention.

Help is appreciated, Thanks!

2 Answers 2

1

try this:

df['New_Date'] = df.groupby('User_Id')['Date'].transform('first')
Sign up to request clarification or add additional context in comments.

Comments

0

If I'm understanding you correctly, just copy the Date column and then use .fillna() with ffill=True. If you post your data as text I can provide example code.

2 Comments

Thanks, but that would not do what I want. Several issues… sometimes the first row is empty and the 2nd row is the one containing value, and other times it is the opposite. and also what about the condition of having the same User_ID.
@dNm your example should demonstrate the full extent of the issue. Your question should have code that creates a dataframe of expected input and another dataframe of expected output. From the sounds of it, the moved goal post involves a group/apply. Should be easy.

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.