Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
165 views
in Technique[技术] by (71.8m points)

python - Best way to compute sequence?

I just started learning pandas and I was trying to figure out the easiest possible solution for the problem mentioned below.

Suppose, I've a dataframe like this ->

A B

6 7

8 9

5 6

7 8

Here, I'm selecting the minimum value cell from column 'A' as the starting point and updating the sequence in the new column 'C'. After sequencing dataframe must look like this ->

A B C 
5 6 0
6 7 1
7 8 2
8 9 3

Is there any easy way to pick a cell from from column 'A' and match it with the matching cell in column 'B' and update the sequence respectively in column 'C'?

Some extra conditions -> If 5 is present in column 'B' then I need to add another row like this -

A B C
0 5 0
5 6 1 
......

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Try sort_values:

df.sort_values('A').assign(C=np.arange(len(df)))

Output:

   A  B  C
2  5  6  0
0  6  7  1
3  7  8  2
1  8  9  3

I'm not sure what you mean with the extra conditions though.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

57.0k users

...