python - 如果根据日期范围在两个不同的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
...
谢谢
解决方案
尝试这个..
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
推荐阅读
- java - 启动 java 方法时在我的 mac 上获取 NSException
- android - 相机应用的全景解决方案
- javascript - multer/filepond 上传返回未定义
- reactjs - Redux 对于 React 和 React Native 是一样的吗?
- asp.net - HTTP 到 HTTPS 不适用于我的 asp.net 网站
- android - Kotlin:RecyclerView with SoundPool:行上没有声音点击
- python - PyQt5区分ok和cancel命令
- doctrine-orm - php bin/console make:entity --regenerate App 不生成新字段
- php - 你能像使用 JavaScript 等那样在 PHP 中拥有非类对象吗?
- java - 在基于时间的解决方案中,消除国际象棋中无趣/输线的最佳方法?