简体   繁体   中英

Pandas conditionally copy values from one column to another row

I have this 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: 像这样!

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!

try this:

df['New_Date'] = df.groupby('User_Id')['Date'].transform('first')

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM