official account : Youer cottage
author :Peter
edit :Peter
Today, I would like to share a question about Pandas topic , Provide a variety of solutions !

There is such a DataFrame( The simulated data is ), Find the index number of the first occurrence of each value :
2 The first occurrence of index is 0
3 The first occurrence of index is 4
7 The first occurrence of index is 6
This is the final result to show , How to solve ? Here are different solutions

shift The function moves the specified length in the specified axis direction :
1、 First move down one unit , obtain df2

2、 For later processing ,df2 Rename the attribute field :
df2.rename(columns={"col1":"col2"},inplace=True)3、 take df1 and df2 A merger

4、 Screening col1 and col2 Different situations can be

The complete line of code is as follows :

Let's disassemble this line of code :
1、 The difference function diff
Each data is subtracted from the previous value ; If two values are equal , The difference is 0

2、 Judgement and 0 The relationship between

3、 Lock to True The value of the can

A very clever way : Direct weight removal , Keep the first piece of data ; But this is only a special case

The requirements are similar , Find the index of the first occurrence of each value ; But the data will appear repeatedly .
The correct results have been marked below :

It can still be solved


result :

It can also solve :

But the de duplication function doesn't work in this case :drop_duplicates A function is a de duplication of the overall data , Keep only one piece of data

Here we will focus on understanding the shift function shift Sum difference function diff The relationship between , Simulate a piece of data :





Take the example of moving one unit by default



Conclusion : Under the same conditions , Original data frame Subtract shift The data generated by the function is diff The result of the function

Under what circumstances will the shift or difference function be used ?

Past highlights
It is suitable for beginners to download the route and materials of artificial intelligence ( Image & Text + video ) Introduction to machine learning series download Chinese University Courses 《 machine learning 》( Huang haiguang keynote speaker ) Print materials such as machine learning and in-depth learning notes 《 Statistical learning method 》 Code reproduction album machine learning communication qq Group 955171419, Please scan the code to join wechat group 