我有一个这样的数据框

Data.head(3)

SD          ED          Buffer
12/1/2020   16/1/2020   3
31/12/2019  12/1/2020   6
4/2/2020    15/2/2020   4

            Data.Dtypes
SD          object
ED          object
Buffer      float64


我想创建两个新列:

Start_Buffer = SD + Buffer
Total_days =(ED-SD) + Buffer


预期产量

Start_Buffer     Total_Days
15/1/2020        7
6/1/2020         18
8/2/2020         15


如何使用熊猫来完成。

最佳答案

试试这个:

Data['ED'] = pd.to_datetime(Data.ED, dayfirst=True) #convert to datetime dtype
Data['SD'] = pd.to_datetime(Data.SD, dayfirst=True) #convert to datetime dtype

Buffer_days = pd.to_timedelta(Data.Buffer, unit='d')
Data['Start_Buffer'] = Data.SD + Buffer_days
Data['Total_Days'] = (Data.ED - Data.SD + Buffer_days ).dt.days


Out[48]:
          SD         ED  Buffer Start_Buffer  Total_Days
0 2020-01-12 2020-01-16     3.0   2020-01-15           7
1 2019-12-31 2020-01-12     6.0   2020-01-06          18
2 2020-02-04 2020-02-15     4.0   2020-02-08          15

关于python-3.x - 如何在 Pandas 的日期字段中添加/减去固定的整数值,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/59762782/

10-12 20:06