If you have datasets and want to do some manipulation then you have to first convert the datasets to dataframe. There are many functions provided by the pandas package that allows you to perform this manipulation. The reshape() function is one of them. Many coders are not able to use it properly and get the error AttributeError: dataframe’ object has no attribute ‘reshape‘ error. In this post, you will know how to solve this error in a simple way.
What does the reshape() function do?
The reshape() function allows you to change the dimension of the existing array or numpy array. Let’s say you have an array or series of 3×2 then you can use this function to change the dimension to 2×3.
What causes the AttributeError: dataframe’ object has no attribute ‘reshape’ error?
The most common reason for getting this error is that you are not properly using the reshape() function on the dataframe. You must be using the reshape() on the entire dataframe or series.
For example, when I will run the below lines of code I will get the error dataframe’ object has no attribute ‘reshape’.
import numpy as np
import pandas as pd
np.random.seed(0)
df = pd.DataFrame({'col1': list('pqrstuvw'), 'col2': np.random.choice(10, 8)})
df["col2"].reshape((-1,4))
Solution for dataframe’ object has no attribute ‘reshape’
The easiest solution to solve this error is you should use this function on the values of the columns, not the entire dataframe or series. To achieve this you will also use the .values on the column.
df["col2"].values.reshape((-1,4))
Now you will not get the AttributeError when you will run the below lines of code.
import numpy as np
import pandas as pd
np.random.seed(0)
df = pd.DataFrame({'col1': list('pqrstuvw'), 'col2': np.random.choice(10, 8)})
df["col2"].values.reshape((-1,4))
Conclusion
Join our list
Subscribe to our mailing list and get interesting stuff and updates to your email inbox.