且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

在DataFrame Pandas中添加带有日期之间的天数的列

更新时间:2023-11-21 21:27:28

假设这些是日期时间列(如果它们不适用to_datetime),则可以减去它们:

Assuming these were datetime columns (if they're not apply to_datetime) you can just subtract them:

df['A'] = pd.to_datetime(df['A'])
df['B'] = pd.to_datetime(df['B'])

In [11]: df.dtypes  # if already datetime64 you don't need to use to_datetime
Out[11]:
A    datetime64[ns]
B    datetime64[ns]
dtype: object

In [12]: df['A'] - df['B']
Out[12]:
one   -58 days
two   -26 days
dtype: timedelta64[ns]

In [13]: df['C'] = df['A'] - df['B']

In [14]: df
Out[14]:
             A          B        C
one 2014-01-01 2014-02-28 -58 days
two 2014-02-03 2014-03-01 -26 days

注意:请确保您使用的是新的熊猫(例如0.13.1),在旧版本中可能无法使用.