I want to update a series if it is missing a key, but my code is generating an error.
This is my code:
for item in list:
if item not in my_series.keys():
my_series = my_series[item] = 0
Where my_series is a series of dtype int64. It's actually a value count.
My code above is generating the following error
'int' object does not support item assignment
CodePudding user response:
What do you mean by "series"? There's no such data type in python if I'm not mistaken. You seem to use it as it was a dict. Do you need to set default value to 0 for a key "item"? If so:
for item in <definitely_list_is_a_bad_name>:
my_series[item] = my_series.get(item) if my_series.get(item, None) is not None else 0
CodePudding user response:
From what I read in the docs, a Pandas series functions much like a dict, so my comment remains valid:
import pandas as pd
d = {'a': 1, 'b': 2, 'c': 3}
my_series = pd.Series(data=d, index=['a', 'b', 'c'])
my_list = ['a','h','c','d']
for item in my_list:
if item not in my_series:
my_series[item] = 0
print(my_series)
# a 1
# b 2
# c 3
# h 0
# d 0
# dtype: int64
Btw, as John Doe mentioned, "list" is a bad choice of a name; don't use Python keywords as objects names, else you will overwrite those keywords and risk problems later.