如何在字典中添加日期到日期?

时间:2018-03-17 05:03:14

标签: python pandas dictionary timedelta

我有一本我用pandas df创建的字典(见下文)。这本词典有一个'键'和日期。我想在字典中的每个日期添加1天。我这样做的一种方法是在df中创建一个新列,该列是一天加上保存日期的列,然后将其存储在字典中。但我有兴趣这样做而无需添加列。

df =  pd.DataFrame({'Key': ['10003', '10003', '10003', '10003', '10003','10003','10034'], 
               'Num1': [12,13,30,12,13,13,16],
               'Num2': [121,122,122,124,125,126,127],
              'admit': [2015019, 20150124, 20150206,20150211,20150220,20150407,20150211],
          'discharge': [20150123, 20150202, 20150211,20150220,20150304,20150410,20150211]})
df['admit'] = pd.to_datetime(df['admit'], format='%Y%m%d')
df['discharge'] = pd.to_datetime(df['discharge'], format='%Y%m%d')

{'10003': {Timestamp('2015-01-09 00:00:00'),
           Timestamp('2015-01-24 00:00:00'),
           Timestamp('2015-02-06 00:00:00'),
           Timestamp('2015-02-11 00:00:00'),
           Timestamp('2015-02-20 00:00:00'),
           Timestamp('2015-04-07 00:00:00')},
'10034': {Timestamp('2015-02-11 00:00:00')}}

d1 = df.groupby('Key')['admit'].apply(set).to_dict() # how the original dictionary is formed above
df['admitplus1'] = ['admit'] + timedelta(days=1)
d2 = df.groupby('Key')['admitplus1'].apply(set).to_dict() # how I formed the new dictionary with an added column to my df

0 个答案:

没有答案