首页 > 解决方案 > 如果根据日期范围在两个不同的df中日期相同,则熊猫设置值

问题描述

我有 df: while disease 是二元列(0 或 1)

diagnosis_date    id  disease
2013-05-03         1     0
2013-05-08         1     0
2013-06-08         1     1
2013-01-01         2     0 
.....

我有日期范围 - 2013-01-01 到 2013-12-31:

date_index=pd.date_range(start='1/1/2013', end='31/12/2013')
dates=pd.DataFrame(date_index,columns=['date'])

我想为df中的每个id,将日期范围设置为date_index,如果日期与诊断日期相同,则在疾病列中设置类似的值,否则该值将设置为零。 愿望df:

date    id    disease
01-01    1       0
02-01     1      0
03-01     1      0
...
05-03     1      0
05-04     1      0
...
06-08    1      1
 ....
12-31     1      0
01-01     2      1
01-02     2      0 
...  

谢谢

标签: pythonpandas

解决方案


尝试这个..

df = pd.read_clipboard() #read in your dataframe from clipboard

dfp = df.pivot('diagnosis_date', 'id', 'disease') #reshape dataframe
dfp.index = pd.to_datetime(dfp.index) #cast index to datetime

dfp.reindex(pd.date_range('1/1/2013','12/31/2013'))\  #add rows with reindex and pd.date_range
   .rename_axis('date').fillna(0)\  #fill with zeroes
   .stack().rename('disease')\  #Reshape back to original shape
   .reset_index()\
   .sort_values(['id', 'date'])  #and sort

输出:

          date  id  disease
0   2013-01-01   1      0.0
2   2013-01-02   1      0.0
4   2013-01-03   1      0.0
6   2013-01-04   1      0.0
8   2013-01-05   1      0.0
..         ...  ..      ...
721 2013-12-27   2      0.0
723 2013-12-28   2      0.0
725 2013-12-29   2      0.0
727 2013-12-30   2      0.0
729 2013-12-31   2      0.0

推荐阅读