Sorry if this is basic but I am new to python.
I was experimenting with creating plots in pandas through a for loop when I got AttributeError: 'tuple' object has no attribute 'plot'.
Looking at my code, I found out that assigning a dataframe to a variable converts it into a tuple. See below:
import seaborn as sns flowers = sns.load_dataset('iris') for k in flowers['species'].unique(): print('1. ', k) print('2. ', type(k)) print('3. ', type(flowers[flowers['species'] == k])) t = flowers[flowers['species'] == k], print('4. ', type(t))
Output:
1. setosa 2. <class 'str'> 3. <class 'pandas.core.frame.DataFrame'> 4. <class 'tuple'> 1. versicolor 2. <class 'str'> 3. <class 'pandas.core.frame.DataFrame'> 4. <class 'tuple'> 1. virginica 2. <class 'str'> 3. <class 'pandas.core.frame.DataFrame'> 4. <class 'tuple'>
This doesn’t happen if I do the same thing outside the for-loop.
print(type(flowers[flowers['species'] == 'setosa'])) o = flowers[flowers['species'] == 'setosa'] print(type(o))
Output:
<class 'pandas.core.frame.DataFrame'> <class 'pandas.core.frame.DataFrame'>
Can someone explain to me python’s assignment logic here? Why is this happening?
Advertisement
Answer
In the for loop,
t = flowers[flowers['species'] == k],
you add an extra comma ,
at the end, and that results:
t = x, x = flowers[flowers['species'] == k] # t is a tuple with one element
tuple defination:
class tuple([iterable]) Tuples may be constructed in a number of ways: Using a pair of parentheses to denote the empty tuple: () Using a trailing comma for a singleton tuple: a, or (a,) Separating items with commas: a, b, c or (a, b, c) Using the tuple() built-in: tuple() or tuple(iterable)