首页 > 解决方案 > 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.

标签: pandaspython-3.5

解决方案


只需映射它:

df['DTCat'] = df['DateType'].map({'2020-01-07': 'NDay', '2020-01-01': 'BM', '2020-02-01': 'NM', '2020-03-01': 'NP1M'})

推荐阅读