Home > Blockchain >  'str' object has no attribute 'str' - not sure why
'str' object has no attribute 'str' - not sure why

Time:11-14

I have the following code.

I want to create a list 'newvalues' containing the number of 'luck' trials ('numberoftrials') on a given date, where this value will equal 0 if there are no 'luck' trials on that date.

However, I get the error 'str' object has no attribute 'str' when I try to check whether a row in the column 'condition' contains the word 'luck'.

I am not sure why this is, given that the 'condition' column does contain strings.

for i in range(0,len(numberofeachconditiononthatdate)): 
     if numberofeachconditiononthatdate['condition'].iloc[i].str.contains('luck'):
        newvalue = numberofeachconditiononthatdate['numberoftrials'].iloc[i]
        newvalues.append(newvalue)
     else:
        newvalues = 0 
        newvalues.append(newvalue)

I would be so grateful for a helping hand!

print(numberofeachconditiononthatdate['condition'].head(10))

0     luck
1    mixed
2    skill
3     luck
4    mixed
5    skill
6     luck
7    mixed
8    skill
9     luck

print(numberofeachconditiononthatdate['numberoftrials'].head(10))

0    5
1    4
2    6
3    1
4    1
5    2
6    1
7    2
8    1
9    3

CodePudding user response:

I solved my issue using an 'if string is in row' method:

for i in range(0,len(numberofeachconditiononthatdate)): 
     if 'luck' in numberofeachconditiononthatdate['condition'].iloc[i]:
        newvalue = numberofeachconditiononthatdate['numberoftrials'].iloc[i]
        newvalues.append(newvalue)
     else:
        newvalue = 0 
        newvalues.append(newvalue)

print(newvalues)

[5, 0, 0, 1, 0, 0, 1, 0, 0, 3, 0, 0, 0, 0, 0, 0, 2, 0, 0, 0, 3, 0, 0, 6, 0, 0]

CodePudding user response:

numberofeachconditiononthatdate['condition'].iloc[i] is a string itself, so you don't need the extra .str, just remove it:

for i in range(0,len(numberofeachconditiononthatdate)): 
     if numberofeachconditiononthatdate['condition'].iloc[i].contains('luck'):
        newvalue = numberofeachconditiononthatdate['numberoftrials'].iloc[i]
        newvalues.append(newvalue)
     else:
        newvalues = 0 
        newvalues.append(newvalue)
  • Related