educative.io

Educative

Code example in the course is deprecated

Hi,
I am at the following code in the course, but it gives error when using tm.makeTimeDataFrame() and also the pandas.util.testing is deprecated. I have the latest version of pandas (2.2.0) installed. What should be the replacement syntax for these to work.

Can you please help?

import pandas.util.testing as tm; tm.N = 3
import numpy as np
import pandas as pd

def unpivot(frame):
N, K = frame.shape
data = {‘value’ : frame.values.ravel(‘F’),
‘variable’ : np.asarray(frame.columns).repeat(N),
‘date’ : np.tile(np.asarray(frame.index), K)}
return pd.DataFrame(data, columns=[‘date’, ‘variable’, ‘value’])
df = unpivot(tm.makeTimeDataFrame())
print(df)

Hi Ozgur Gurgun,
To address the issues in your code, let’s replace the deprecated pandas.util.testing with pandas.testing and also replace tm.makeTimeDataFrame() with direct DataFrame creation using NumPy.
Here’s the corrected code:

import pandas.testing as tm  # Replace pandas.util.testing with pandas.testing
import numpy as np
import pandas as pd

tm.N = 3  # Set the number of rows to 3

def unpivot(frame):
    N, K = frame.shape
    data = {'value': frame.values.ravel('F'),
            'variable': np.asarray(frame.columns).repeat(N),
            'date': np.tile(np.asarray(frame.index), K)}
    return pd.DataFrame(data, columns=['date', 'variable', 'value'])

# Generate sample time series DataFrame using pandas DataFrame directly
dates = pd.date_range('2024-01-01', periods=3)
df = pd.DataFrame(np.random.randn(3, 3), index=dates, columns=['A', 'B', 'C'])

# Use the unpivot function
df_unpivoted = unpivot(df)
print(df_unpivoted)

In this corrected code:
We’ve replaced pandas.util.testing with pandas.testing.
tm.makeTimeDataFrame() is replaced with direct DataFrame creation using pd.DataFrame(np.random.randn(3, 3), index=dates, columns=['A', 'B', 'C']) to generate sample time series data.

Hi Muhammad, many thanks for getting back on this. After some investigation, that was my exact conclusion for the replacement code as well. The course material needs to be updated though so that the new learners do not waste time on these examples. It is a great learning site but things like this put me off a little bit. I hope that the overseeing people are reading these comments as serious feedback.
Many thanks again.
Ozgur