[英]Pandas conditionally copy values from one column to another row
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.我想将 Date 列的值复制到 New_Date 列,但不仅复制到完全相同的行,我还想复制到具有相同 User_ID 值的每一行。
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.我尝试了 groupby 然后复制,但是 groupby 使所有值都变成了列表,并且具有相同 user_id 的其他列可以在不同的行中具有不同的值,然后它搞砸了很多事情。
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
.如果我理解正确,只需复制 Date 列,然后将
.fillna()
与ffill=True
一起使用。 If you post your data as text I can provide example code.如果您将数据作为文本发布,我可以提供示例代码。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.