pandas - Create category column based on data from another column
问题描述
I have a python dataframe df as:
Pkg DateType
Date
2020-01-07 2.39 2020-01-07
2020-01-08 4.20 2020-01-09
2020-01-19 7.49 2020-02-01
2020-01-20 7.49 2020-03-01
I want the following:
Pkg DateType DTCat
Date
2020-01-07 2.39 2020-01-07 NDay
2020-01-08 4.20 2020-01-01 BM
2020-01-19 7.49 2020-02-01 NM
2020-01-20 7.49 2020-03-01 NP1M
where the column DTCat
is created based on the following dictionary condition applied to column DateType
{'2020-01-07': 'NDay', '2020-01-01': 'BM', '2020-02-01': 'NM', '2020-03-01': 'NP1M'}
I am not sure how to apply the conditions to the column in the above dataframe.
解决方案
只需映射它:
df['DTCat'] = df['DateType'].map({'2020-01-07': 'NDay', '2020-01-01': 'BM', '2020-02-01': 'NM', '2020-03-01': 'NP1M'})
推荐阅读
- java - “java 动态 web 项目”和“Gradle 项目”有什么区别
- python - 如何在 clipspy 中获取事实值并将其存储在 python 变量中
- python - 错误:[Errno 13] Permission denied: './configure' when using pip3 install matplotlib on termux
- javascript - 我想从点击功能复制参数
- c++ - 如何在 OpenGL 中使用 Perlin Noise 生成程序地形?
- javascript - 使用 swiper.js 库做出反应的 CSS 冲突
- javascript - javascript中this关键字的默认绑定?
- audio - 修改一些代码以将 ffmpeg / concat 不同的音频格式转换为 1 个长 WAV 文件
- reactjs - 为什么 setState 不改变值?
- kubernetes - GCP 上的 Kubernetes 集群缺少编辑权限