I have the following code. I am trying to select the 4th (index) item from a list at a given index location of the dataframe 'df'.
trialoutcomes = []
for j in range(0,len(df.columns)):
for i in range(5,len(df)):
trialoutcome = df.loc[i,j]
trialoutcomes.append(trialoutcome[4])
However, I keep getting the error: ''float' object is not subscriptable', although I am not sure as to why.
When I take the code out of the loop below and enter the following code, I get the output I want, indicating a 'fullMiss' trial.
easy = df.loc[5,0]
print(easy[4])
fullMiss
However, in the context of the loop above this does not work.
When I enter:
df.loc[5,0]
This prints:
['trial', '2:7|2:8|4:1|4:2|8:3|8:4|', '4:7', '4:7', 'fullMiss', '5.828', '11', '37', '66']
I would be so grateful for a helping hand!
The first 10 rows of the 'df' dataframe looks something like this:
0 ... 77
5 [trial, 2:7|2:8|4:1|4:2|8:3|8:4|, 4:7, 4:7, fu... ... [trial, 7:4|7:5|2:2|3:2|2:7|2:8|, 4:3, 3:4, fu...
6 [trial, 2:3|3:3|7:6|8:6|3:7|3:8|, 2:7, 2:7, ne... ... [trial, 4:8|5:8|7:3|8:3|2:2|3:2|, 6:2, 6:2, ne...
7 [trial, 3:6|4:6|1:1|1:2|5:2|6:2|, 3:7, 4:6, hi... ... [trial, 5:5|5:6|3:1|4:1|1:6|1:7|, 6:7, 7:8, fu...
8 [trial, 8:5|8:6|1:7|1:8|7:1|8:1|, 2:2, 2:1, fu... ... [trial, 3:3|4:3|2:7|2:8|6:7|7:7|, 4:6, 3:6, ne...
9 [trial, 5:8|6:8|4:3|5:3|9:2|9:3|, 5:3, 5:3, hi... ... [trial, 7:2|7:3|1:4|1:5|5:7|6:7|, 3:4, 4:5, fu...
10 [trial, 1:5|2:5|6:2|7:2|8:7|9:7|, 2:5, 1:6, ne... ... [trial, 7:2|7:3|1:1|2:1|5:7|6:7|, 5:8, 5:9, fu...
11 [trial, 2:2|2:3|4:7|5:7|8:2|8:3|, 4:2, 5:3, fu... ... [trial, 1:3|2:3|5:8|5:9|9:2|9:3|, 5:6, 4:5, fu...
12 [trial, 2:2|2:3|5:9|6:9|8:2|8:3|, 6:5, 7:6, fu... ... [trial, 2:3|2:4|7:4|7:5|8:9|9:9|, 6:8, 6:9, fu...
13 [trial, 2:4|3:4|8:8|9:8|7:2|8:2|, 8:8, 8:9, ne... ... [trial, 2:2|3:2|7:7|7:8|7:3|8:3|, 4:5, 4:5, fu...
14 [trial, 7:5|8:5|3:4|3:5|6:9|7:9|, 7:4, 7:3, fu... ... [trial, 6:3|6:4|3:9|4:9|2:2|2:3|, 4:8, 4:9, hi...
CodePudding user response:
i think your data contain nans:
a=['trial', '2:7|2:8|4:1|4:2|8:3|8:4|', '4:7', '4:7', 'fullMiss', '5.828', '11', '37', '66']
print(a[4]) #fullMiss
a=np.nan
print(a[4]) #TypeError: 'float' object is not subscriptable
you can drop nans or you can add a control in loop:
for j in range(0,len(df.columns)):
for i in range(5,len(df)):
trialoutcome = df.loc[i,j]
trialoutcomes.append(trialoutcome[4] if type(trialoutcome) ==list else None)
CodePudding user response:
I imagine the error doesn't happen on 5,0. From what I can tell, you might be overdrawing your index - range(0, len(df.columns)) would end with an index beyond your last column index, and should instead be range(0, len(df.columns) - 1), I think? Same for len(df). If that all is hogwash, it might help to do print(i,j) when you actually run, to see where it's stumbling. Perhaps you'll find a 'float'.