Pandas - AttributeError: '_iLocIndexer' object has no attribute 'sector' - python

I've built a sample code, to see if things worked as I wanted.
predictorgroups=predictor.groupby("sector")
targetco=target.iloc[1]
group=predictorgroups.get_group(targetco.sector).astype(object)
pdf=(group).sort('size',ascending=False)[:10].astype(object)
It worked fine. So I wanted to upgrade and make that code interact multiple times, so I adapted it to:
for i in range(len(target.index[:10])):
predictorgroups=predictor.groupby("sector")
targetco=target.iloc(i)
group=predictorgroups.get_group(targetco.sector).astype(object)
pdf=(group).sort('size',ascending=False)[:10].astype(object)
Note that this one is the very same code as the above. However in the second one I'm getting this error:
Traceback (most recent call last):
File "/file.py", line 64, in <module>
group=predictorgroups.get_group(targetco.sector).astype(object)
AttributeError: '_iLocIndexer' object has no attribute 'sector'
I noticed that in the first code, if I print targetco I get a Pandas Series with only one index. If I do the same in the second one, I get the following object type:
targetco pandas.core.indexing._iLocIndexer object at 0x105a3e438
Can anyone explain to me why is that happening? Why I'm getting a different response in the second code if they are both the same?

I think there is typo, change () to []:
targetco=target.iloc(i)
to
targetco=target.iloc[i]
Because:
targetco = target.iloc(1)
print (targetco)
<pandas.core.indexing._iLocIndexer object at 0x000000000A8CD358>
and then pandas.core.indexing._iLocIndexer object has no column sector, so raise error:
print (targetco.sector)
AttributeError: '_iLocIndexer' object has no attribute 'sector'

Related

Problem with making a Reddit bot in python

I'm trying to program a reddit bot, but get this error message:
Traceback (most recent call last):
File "main.py", line 64, in <module>
run_bot(r, comments_replied_to)
File "main.py", line 34, in run_bot
comments_replied_to.append(comment.id)
AttributeError: 'filter' object has no attribute 'append'
Here is my code: https://pastebin.com/caz14jm7
I think I have to change append into a list, but I don't know how to do that
Part of this is a version difference. In Python 2, filter returned a list. In Python 3, filter returns a generator, which you are treating like a list. The filter generator does not have an append method.
So, you just need to turn it into a list:
comments_replied_to = list(filter(None, comments_replied_to))
Or, even better (in the opinion of many):
comments_replied_to = [k for k in comments_replied_to if k]
I have 2 potential solutions for you,
solution 1:
Line 55 You can change like this
comments_replied_to = List(filter(None, comments_replied_to))
so that, your get_saved_comments() will return a list.
This will help you use the append method and comments_replied_to.append(comment.id) should work without any error
Solution 2:
Line 60: You can change like this
comments_replied_to = list(get_saved_comments())
As long as comments_replied_to is a list type, it will allow you to append method without any issues.
check this blog to have a better understanding over append method
https://www.programiz.com/python-programming/methods/list/append

Object has no attribute 'split()' Python

Having an error where i'm trying to get the first work from a string that is passed in to a method within a class. But i am getting AttributeError: 'Deck' object has no attribute 'split' when I run. The 'new_card' that is passed in will be for example 'Two of Hearts'. and new_Card is a string and self.values is a dictionary
# returns integer value of a card
def get_card_value(self, new_card):
return self.values[new_card.split()[0]]
and the error:
Traceback (most recent call last):
File "/home/andypaling/Documents/Programming/python/random/card_game/game.py", line 146, in
if not Game.check_same_cards(player1_deck, player2_card):
File "/home/andypaling/Documents/Programming/python/random/card_game/game.py", line 87, in check_same_cards
if card1.get_card_value(card1) == card2.get_card_value(card2):
File "/home/andypaling/Documents/Programming/python/random/card_game/game.py", line 40, in get_card_value
split_string = new_card.split(' ')
thanks for any help
Hey it seems like you are using a diffrent data type and not a string in your case judging that your making a card game i am guessing you are using a tuple. Try converting the data to a string then split it using the .split() function.
I hope this can help.

Conversion of string to dictionary

I have captured a string from a REST get request and have placed it in a variable. The string is:
{"name":"na1mailboxarchive","objectCount":49564710,"dataBytes":36253526882451},{"name":"na1mailboxarchive2","objectCount":17616567,"dataBytes":13409204616615}
I am trying to convert it to a dictionary so I can increment through it and capture the bucket name, size and object count. I have tried eval()
bucket_dict = eval(bucket_info)
but the program errors out with a:
Traceback (most recent call last):
File "./test.py", line 83, in <module>
for k,b in bucket_dict.items():
AttributeError: 'tuple' object has no attribute 'items'
When I print the value of bucket_dict I get:
({'name': 'na1mailboxarchive', 'objectCount': 49564710, 'dataBytes': 36253526882451}, {'name': 'na1mailboxarchive2', 'objectCount': 17616567, 'dataBytes': 13409204616615})
I think the foul up is the () at the beginning and the end of the dictionary. Nothing else I have tried works either.
Try this instead
import ast
string = '{"name":"na1mailboxarchive","objectCount":49564710,"dataBytes":36253526882451},{"name":"na1mailboxarchive2","objectCount":17616567,"dataBytes":13409204616615}'
result = ast.literal_eval(string)
print(result)
result is returned as a dictionary
I got it figured out.
Firstly the json return from the REST API get is badly formatted. I will take that up with the vendor. Secondly I used some iof the infrmation form #PrashantKumar and #MisterMiyagi to sus out the issue I was having. In my original code I had loaded the list with:
bucket_info = [acct_string[acct_string_start+11:acct_len-4]]
The variable was capturing the leading "[" and trailing "]" as a part of the string. Once I removed them then the list behaved correctly and I now can work with it. Thank you for the information and the trail markers.

Clarification on Protobuf PrintField()

I'm trying to use the Google Protobuf API found here and I'm having trouble with the built in PrintField() method with the following info:
PrintField(field, value, out, indent=0, as_utf8=False, as_one_line=False)
Print a single field name/value pair. For repeated fields, the value should be a single element.
After merging my message, I'm able to print out the fully merged layout. However, I'd like the specific field/value pair and I'm a bit unsure how to go about doing that as I can't find any full fledged internet examples.
I have tried the following:
proto.PrintField(1, 1, cStringIO.StringIO())
, proto.PrintField('field1', 'subfield', cStringIO.StringIO())
Where my message looks like:
message field1 {subfield = 1;}
Running as such yields the following error: "AttributeError: 'int' object has no attribute 'is_extension'" this is the same in both cases, the only change being 'int' or 'string'.

'string indices must be integers' error with this JSON dict

I have a dictionary with a single item in it created using json.loads(). The data structure looks like this:
{"teamId":96}
When I attempt to access the dictionary value by using the following:
mydict = mydict[u'teamId']
I get the following error:
Traceback (most recent call last):
File "C:\Python27\counter.py", line 65, in <module>
print home_team[u'teamId']
TypeError: string indices must be integers
Can anyone explain to me what the issue is here? The code looks like it should work to me.
Thanks
You need json.dumps(you_file) :
json.loads(json.dumps(your_file))

Categories