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:
JavaScript
x
10
10
1
import seaborn as sns
2
flowers = sns.load_dataset('iris')
3
4
for k in flowers['species'].unique():
5
print('1. ', k)
6
print('2. ', type(k))
7
print('3. ', type(flowers[flowers['species'] == k]))
8
t = flowers[flowers['species'] == k],
9
print('4. ', type(t))
10
Output:
JavaScript
1
13
13
1
1. setosa
2
2. <class 'str'>
3
3. <class 'pandas.core.frame.DataFrame'>
4
4. <class 'tuple'>
5
1. versicolor
6
2. <class 'str'>
7
3. <class 'pandas.core.frame.DataFrame'>
8
4. <class 'tuple'>
9
1. virginica
10
2. <class 'str'>
11
3. <class 'pandas.core.frame.DataFrame'>
12
4. <class 'tuple'>
13
This doesn’t happen if I do the same thing outside the for-loop.
JavaScript
1
4
1
print(type(flowers[flowers['species'] == 'setosa']))
2
o = flowers[flowers['species'] == 'setosa']
3
print(type(o))
4
Output:
JavaScript
1
3
1
<class 'pandas.core.frame.DataFrame'>
2
<class 'pandas.core.frame.DataFrame'>
3
Can someone explain to me python’s assignment logic here? Why is this happening?
Advertisement
Answer
In the for loop,
JavaScript
1
2
1
t = flowers[flowers['species'] == k],
2
you add an extra comma ,
at the end, and that results:
JavaScript
1
5
1
t = x,
2
x = flowers[flowers['species'] == k]
3
4
# t is a tuple with one element
5
tuple defination:
JavaScript
1
8
1
class tuple([iterable])
2
Tuples may be constructed in a number of ways:
3
4
Using a pair of parentheses to denote the empty tuple: ()
5
Using a trailing comma for a singleton tuple: a, or (a,)
6
Separating items with commas: a, b, c or (a, b, c)
7
Using the tuple() built-in: tuple() or tuple(iterable)
8