0
0
Pandasdata~5 mins

diff() for differences in Pandas - Cheat Sheet & Quick Revision

Choose your learning style9 modes available
Recall & Review
beginner
What does the diff() function do in pandas?

The diff() function calculates the difference between consecutive rows or elements in a pandas Series or DataFrame.

Click to reveal answer
beginner
How do you calculate the difference between rows in a DataFrame using diff()?

Call diff() on the DataFrame. By default, it subtracts the previous row from the current row for each column.

Click to reveal answer
intermediate
What does the periods parameter in diff() control?

The periods parameter sets how many rows (or elements) to go back when calculating the difference. For example, periods=2 subtracts the value two rows above.

Click to reveal answer
beginner
What happens if the first row has no previous row when using diff()?

The first row will have a NaN value because there is no previous row to subtract from.

Click to reveal answer
beginner
Can diff() be used on a pandas Series? What is the result?

Yes, diff() works on a Series and returns a new Series with the difference between each element and the previous one.

Click to reveal answer
What does df.diff() compute by default?
ASum of all rows
BCumulative sum of rows
CDifference between columns
DDifference between each row and the previous row
What value does diff() return for the first row?
ANaN
B1
C0
DSame as first row
How do you calculate the difference between a row and the row two places above using diff()?
A<code>df.diff(axis=1)</code>
B<code>df.diff(periods=1)</code>
C<code>df.diff(periods=2)</code>
D<code>df.diff(periods=-2)</code>
Can diff() be applied to a pandas Series?
ANo, only DataFrames
BYes, it returns differences between elements
CYes, but returns the sum
DNo, it causes an error
What does df.diff(axis=1) do?
ACalculates difference between columns for each row
BCalculates difference between rows for each column
CCalculates cumulative sum
DReturns the original DataFrame
Explain how the diff() function works in pandas and give an example of when you might use it.
Think about how you find change from one day to the next in a list of numbers.
You got /4 concepts.
    Describe the role of the periods parameter in diff() and how changing it affects the output.
    Imagine looking back more than one step to find differences.
    You got /4 concepts.