熊猫基于位置列创建新类别,无需 for 循环

时间:2021-06-10 07:39:11

标签: python pandas linux-df

我的一列表示一个人的 x 距离看起来像这样:

x_distance = [0.01, 0.321, 2.576, 0.41, 2.11, 2.62]

我想创建一个列,创建一个新的类别,如果x_distance中有大于2.5的值,不使用for循环(注意x_distance的顺序) 对于 x_distance 正确答案是:

x_distance_groups = [0, 0, 1, 1, 1, 2]

1 个答案:

答案 0 :(得分:1)

我想您有一个包含 df 列的数据框 x_distance

>>> df["x_distance"].gt(2.5).cumsum()

0    0
1    0
2    1
3    1
4    1
5    2
Name: x_distance, dtype: int64