python - 使用 pandas 对列中的重复值进行分类

标签 python pandas pandas-groupby

我有一个数据框,数据框中有一列名称为“压力”,它具有重复值,我想对其进行分类。我有这样的专栏 enter image description here

pressure
0.03
0.03
0.03
2.07
2.07
2.07
3.01
3.01

我尝试过 groupby() 方法,但无法创建分段列。我认为这是 Pandas 的一种简单方法,任何人都可以帮助我。 我需要这样的输出 enter image description here

Pressue   Segment
0.03      1
0.03      1
0.03      1
2.07      2
2.07      2
2.07      2
3.01      3
3.01      3

提前致谢

最佳答案

使用factorize如果性能很重要:

data["Segment"]= pd.factorize(data["pressure"])[0] + 1
print (data)
   pressure  Segment
0      0.03        1
1      0.03        1
2      0.03        1
3      2.07        2
4      2.07        2
5      2.07        2
6      3.01        3
7      3.01        3

性能:

data = pd.DataFrame({'pressure': np.sort(np.random.randint(1000, size=10000)) / 100})

In [312]: %timeit data["pressure"].replace({j: i for i,j in enumerate(data["pressure"].unique(),start=1)}).astype("int")
141 ms ± 3.11 ms per loop (mean ± std. dev. of 7 runs, 10 loops each)

In [313]: %timeit pd.factorize(data["pressure"])[0] + 1
751 µs ± 3.97 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)

关于python - 使用 pandas 对列中的重复值进行分类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60414107/

相关文章:

python - 按排序顺序检索 sqlalchemy 关系对象

python - 如何在 Keras 中将输入拆分为不同的 channel

python - 在基于 Python 文本的 GUI (TUI) 中输入

python - 在 Python 中使用 pandas 对过滤后的数据应用过滤器

python - 分组依据这个或那个

python - lambda - 无法将 datetime.date 与 int 进行比较

python - 按组查看趋势变化(python pandas 数据框)

python - 根据具有特定值的行创建新数据框

python - 如何在不排序的情况下迭代组?

python - PANDAS - 为多个列正确执行嵌套分组(几列构成唯一标识符)