简体   繁体   English

Python:根据 dataframe 中的现有列添加带有日期的新列

[英]Python : Add a new column with date based on existing column in dataframe

have a df with values:有一个带有值的df:

   name        date
0   tom  01-07-2006
1   tom  07-07-2006
2   tom  13-07-2006
3   tom  19-07-2006
4  mark  01-07-2006
5  mark  07-07-2006
6  mark  13-07-2006
7  mark  19-07-2006

How to add a column min date which is minimum of date + 1如何添加min date的列最小日期+ 1

expected_output:预期输出:

   name        date  min date
0   tom  01-07-2006  02-07-2006
1   tom  07-07-2006  02-07-2006
2   tom  13-07-2006  02-07-2006
3   tom  19-07-2006  02-07-2006
4  mark  02-07-2006  03-07-2006
5  mark  07-07-2006  03-07-2006
6  mark  13-07-2006  03-07-2006
7  mark  19-07-2006  03-07-2006

Convert column to datetimes, then get minimal per groups by GroupBy.transform and last add 1 day by Timedelta :将列转换为日期时间,然后通过GroupBy.transform Timedelta 1 天:

df['date'] = pd.to_datetime(df['date'], dayfirst=True)

df['min date'] = df.groupby('name')['date'].transform('min') + pd.Timedelta(1, 'd')
print (df)
   name       date   min date
0   tom 2006-07-01 2006-07-02
1   tom 2006-07-07 2006-07-02
2   tom 2006-07-13 2006-07-02
3   tom 2006-07-19 2006-07-02
4  mark 2006-07-02 2006-07-03
5  mark 2006-07-07 2006-07-03
6  mark 2006-07-13 2006-07-03
7  mark 2006-07-19 2006-07-03

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 根据现有列的条件语句向熊猫数据框添加新列 - Add new column to a pandas dataframe based on conditional statement of existing column Python Pandas Dataframe:基于现有列添加新列,其中包含列表列表 - Python Pandas Dataframe: add new column based on existing column, which contains lists of lists 将列添加到现有 dataframe 并将数据导入到 Python 中的新列 Pandas - Add column to existing dataframe and import data into new column in Python Pandas 如何根据列值在现有数据框中添加新行? - How to add new rows in existing dataframe based on the column values? 如何基于Python数据框中现有的值向新列添加值? - How can I add a value to a new column based on a value existing in my dataframe in Python? 基于现有 python pandas 列的新数据框 - new dataframe based on column from existing python pandas 如何根据python中现有列中的条件创建新列? - How to create a new column based on conditions in the existing columns in a dataframe in python? 将新的列元素显式添加到Pandas DataFrame(Python 2)中的现有行 - Add new column elements to explicitly to existing row in Pandas DataFrame (Python 2) 根据日期列范围将列添加到数据框 - Add column to dataframe based on date column range 基于 Python 中现有字符串列的新列 - New column based on existing string column in Python
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM