Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python: Pandas Dataframe AttributeError: 'numpy.ndarray' object has no attribute 'fillna'

Since I am creating a dataframe, I don't understand why I am getting an array error.

M2 = df.groupby(['song_id', 'user_id']).rating.mean().unstack()
M2 = np.maximum(-1, (M - 3).fillna(0) / 2.)  # scale to -1..+1  (treat "0" scores as "1" scores)
M2.head(2)

AttributeError: 'numpy.ndarray' object has no attribute 'fillna'
like image 821
jeangelj Avatar asked Jun 03 '16 23:06

jeangelj


People also ask

How do I check if an array is equal in NumPy?

Use numpy.array_equiv() function to check whether two arrays are equal or not in Python. This function returns True if both arrays have the same shape and all the elements are equal and return False otherwise.

How can you create a NumPy array?

The array object in NumPy is called ndarray . We can create a NumPy ndarray object by using the array() function.

How do I check if two arrays are equal in Python?

Check if two arrays are equal or not using SortingSort both the arrays. Then linearly compare elements of both the arrays. If all are equal then return true, else return false.

How do you turn an array into a DataFrame?

To convert an array to a dataframe with Python you need to 1) have your NumPy array (e.g., np_array), and 2) use the pd. DataFrame() constructor like this: df = pd. DataFrame(np_array, columns=['Column1', 'Column2']) . Remember, that each column in your NumPy array needs to be named with columns.


2 Answers

(M - 3) is getting interpreted as a numpy.ndarray. This implies that M is defined somewhere as a numpy.ndarray. Test it out by running:

print type(M)
like image 166
piRSquared Avatar answered Sep 16 '22 15:09

piRSquared


You are calling the .fillna() method on a numpy array. And numpy arrays don't have that method defined.

You can probably convert the numpy array to a pandas.DataFrame and then apply the .fillna() method.

like image 30
Kedaar Rao Avatar answered Sep 19 '22 15:09

Kedaar Rao