How to Fix AttributeError: ‘DataFrame’ object has no attribute ‘reshape’

AttributeError: ‘DataFrame’ object has no attribute ‘reshape’ error typically occurs when you try to “use the reshape() method on a Pandas DataFrame.” The reshape() method is used to change the shape of a NumPy array, but it is not defined for DataFrames.

To fix the AttributeError: ‘DataFrame’ object has no attribute ‘reshape’ error, you can use the “pivot()”“melt()”, “.values” or other reshaping methods provided by Pandas, depending on what you want to achieve.

Reproduce the error

import pandas as pd

df = pd.DataFrame({'a': [1, 2, 3, 4], 'b': [5, 6, 7, 8]})

df1 = df.reshape()

print(df1)

Output

AttributeError: 'DataFrame' object has no attribute 'reshape'

How to fix it?

Here are three ways to fix the AttributeError: ‘DataFrame’ object has no attribute ‘reshape’ error.

  1. Using “df[‘col’].values.reshape()”
  2. Using “df.pivot()”
  3. Using “df.melt()”

Solution 1: Using df[‘col’].values.reshape() method

The easiest solution to fix the error is using the reshape() function on the values of the columns, not the entire dataframe or series.

import pandas as pd

df = pd.DataFrame({'a': [1, 2, 3, 4], 'b': [5, 6, 7, 8], c: [9, 10, 11, 12]})

reshaped_df = df['b'].values.reshape(2, 2)

print(reshaped_df)

Output

[[5 6]
 [7 8]]

Solution 2: Using the df.pivot() method

The pivot() method ” converts a long-form DataFrame, where each row represents a single observation, into a wide-form DataFrame, where each unique value in a column becomes a new column in the resulting DataFrame.”

import pandas as pd

df = pd.DataFrame({'a': [1, 2, 3, 4],
                   'b': [5, 6, 7, 8],
                   'c': [9, 10, 11, 12]})

reshaped_df = df.pivot(index='a', columns='b', values='c')

print(reshaped_df)

Output

Using the df.pivot() method

Solution 3: Using the df.melt() method

The df.melt() method is used to do the opposite, converting a wide-form DataFrame into a long-form DataFrame.

import pandas as pd

df = pd.DataFrame({'a': [1, 2, 3, 4],
                   'b': [5, 6, 7, 8],
                   'c': [9, 10, 11, 12]})

df_melted = df.melt(id_vars='a', value_vars=['b', 'c'])

print(df_melted)

Output

Using the df.melt() method

That’s it!

Related posts

AttributeError: ‘DataFrame’ object has no attribute ‘iteritems’

AttributeError: ‘DataFrame’ object has no attribute ‘ix’

AttributeError: ‘DataFrame’ object has no attribute ‘dtype’

AttributeError: ‘DataFrame’ object has no attribute ‘split’

AttributeError: ‘DataFrame’ object has no attribute ‘concat’

Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.