首页 > 解决方案 > 创建一个新列,该列取决于熊猫中其他列的值范围

问题描述

我有一个示例熊猫数据框:

datetime               column1
2021.04.10 01:00:00.    10
2021.04.11 02:00:00     15
2021.04.11 03:00:00.     5
2021.04.11 04:00:00.    20
2021.04.11 05:00:00.    15
2021.04.11 06:00:00.    2

我想创建一个名为 position 的新列,如果 clolumn1 的值小于 10,则为 25%,当 column1 值 >=10 和 <15 时,值为 40%,当 column1 值为 100% 时,值为>=15。

示例输出如下所示:

datetime               column1.  position
2021.04.10 01:00:00.    10.        40%
2021.04.11 02:00:00     15.        100%
2021.04.11 03:00:00.     5.         25%
2021.04.11 04:00:00.    20.         100%
2021.04.11 05:00:00.    15.         100%
2021.04.11 06:00:00.    2.          25%

标签: pythonpandasnumpydata-science

解决方案


pd.cut

这是一种pd.cut用于将值分类/分类为column1具有预定义标签的离散间隔的方法。

df['position'] = pd.cut(df['column1'], 
                        bins=[-np.inf, 10, 15, np.inf], 
                        labels=['25%', '40%', '100%'], right=False)

               datetime  column1 position
0  2021.04.10 01:00:00.       10      40%
1  2021.04.11 02:00:00        15     100%
2  2021.04.11 03:00:00.        5      25%
3  2021.04.11 04:00:00.       20     100%
4  2021.04.11 05:00:00.       15     100%
5  2021.04.11 06:00:00.        2      25%

推荐阅读