简体   繁体   English

Pandas 有条件地将值从一列复制到另一行

[英]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 值的每一行。

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.我尝试了 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.

相关问题 根据 Pandas 中的列值将内容从一个 Dataframe 复制到另一个 Dataframe - Copy contents from one Dataframe to another based on column values in Pandas 有条件地将一个 DataFrame 列中的值替换为另一列中的值 - Conditionally replacing values in one DataFrame column with values from another column 如何根据 pandas 中两个不同列的条件将值从一列复制到另一列? - how to copy values from one column into another column based on conditions of two different columns in pandas? 创建一个新的 pandas dataframe 列,其中包含一个附加值,然后是其下方另一列的值的副本 - Creating a new pandas dataframe column with one added value, then a copy of values from another column underneath it 如何按列分组并将组中的所有值复制到pandas中的一行? - How to group by column and copy all values of a group to one row in pandas? 将条件值从一列复制到另一列 - Copy conditional values from one column to another 将值从一个 dataframe 列复制到另一列 - Copy values from one dataframe column to another 根据Pandas中的特定条件将值从一列复制到同一行中的其他列 - Copy values from one column to other columns in same row based on specific criteria in Pandas 如何根据 Pandas 中的条件将一列的值复制到另一列? - How to copy values of one column to another based on condition in Pandas? 在熊猫中将值从一列追加到另一列 - Appending values from one column to another in pandas
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM