Mehran Rasheed
Mehran Rasheed

Reputation: 33

Categorize the repetitive values in a column using pandas

I have a Dataframe and I have one column in data frame name 'Pressure' it has repetitive value and I want categorize it. I have column like this enter image description here

pressure
0.03
0.03
0.03
2.07
2.07
2.07
3.01
3.01

I have tried groupby() method but not able to make a segment column. I think is a easy way in panda can anybody help me in this. I need an output like this 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

Thanks in advance

Upvotes: 2

Views: 70

Answers (2)

jezrael
jezrael

Reputation: 862681

Use factorize if performance is important:

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

Performance:

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)

Upvotes: 3

Sociopath
Sociopath

Reputation: 13401

Create dict with unique values from a column pressure and label corresponding the same then use replace

d = {j: i for i,j in enumerate(data["Pressure"].unique(),start=1)}

data["Segment"]= data["Pressure"].replace(d).astype("int")
print(data)

Output:

Pressure   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

Upvotes: 2

Related Questions