def categorise_sourceIP(df):
df_sIPf = pd.df.sourceIP.value_counts()
df_sIPf['counts'] = np.array(df.sourceIP.value_counts())
df_sIPf['sourceIP'] = df_sIPf.index
df_sIPf.reset_index(level=0,inplace=True,drop=True)
counts_cate = []
for num in df_sIPf['counts']:
if num in range(0,21):
counts_cate.append('<20')
elif num in range(21,201):
counts_cate.append('21-200')
elif num in range(201,401):
counts_cate.append('201-400')
elif num > 400:
counts_cate.append('>400')
counts_cate=df_sIPf['categorised_count']
The error call back is the following
NameError Traceback (most recent call last)
<ipython-input-11-9622f76efabe> in <module>
27 elif num > 400:
28 counts_cate.append('>400')
---> 29 counts_cate=df_sIPf['categorised_count']
NameError: name 'df_sIPf' is not defined
How do I fix this? At a key stage in my problem set.
Essentially trying to build a relationship between clusters of two different variables in the dataframe so a similar piece of code will be written for the second set.
You need to return df_sIPf from your function if you want it to be accessible outside that function:
def categorise_sourceIP(df):
df_sIPf = pd.df.sourceIP.value_counts()
df_sIPf['counts'] = np.array(df.sourceIP.value_counts())
df_sIPf['sourceIP'] = df_sIPf.index
df_sIPf.reset_index(level=0,inplace=True,drop=True)
counts_cate = []
for num in df_sIPf['counts']:
if num in range(0,21):
counts_cate.append('<20')
elif num in range(21,201):
counts_cate.append('21-200')
elif num in range(201,401):
counts_cate.append('201-400')
elif num > 400:
counts_cate.append('>400')
return df_sIPf
counts_cate = categorise_sourceIP(df)['categorised_count']
Related
im doing python code using machine learning support vector machins(svm) model for predict, i used a bank dataset from kaggle
so this is the code and the error dicated in the 4th row
`encoded_data = [0] * len(data_to_predict)
for i in range(len(data_to_predict)):
if i == 0:
encoded_data[i] = gen[data_to_predict[i]]
elif i==1:
encoded_data[i] = m[data_to_predict[i]]
elif i==2:
encoded_data[i] = ed[data_to_predict[i]]
elif i==3:
encoded_data[i] = s_emp[data_to_predict[i]]
elif i==4:
encoded_data[i] = d[data_to_predict[i]]
elif i==10:
encoded_data[i] = a[data_to_predict[i]]
else:
encoded_data[i] = s.fit_transform(np.array(encoded_data[i]).reshape(-1,1))`
this is the error why dose it shows 'male' what am i supposed to change or add??
`KeyError Traceback (most recent call last)
<ipython-input-68-e2388fb9ed49> in <module>
2 for i in range(len(data_to_predict)):
3 if i == 0:
----> 4 encoded_data[i] = gen[data_to_predict[i]]
5 elif i==1:
6 encoded_data[i] = m[data_to_predict[i]]
> KeyError: 'male'`
what does your data_to_predict look like. What I understand from the provided information is on this line encoded_data[i] = gen[data_to_predict[i]] the data_to_predict[i] returns 'male' and there is no key named 'male' in gen.
I am trying to make a binary tree using lists, but it is showing me this error, can you help me with this?
class BT:
def __init__(self, lp , data , rp):
self.LeftPointer = lp
self.data = data
self.RightPointer = rp
def insert(x):
#current_position
c = 0
#temporary_position
t = 0
while True:
if dsBT[c].data == None :
dsBT[c].data = x
break
elif x > dsBT[c].data:
if dsBT[c].RightPointer == 0:
t = c
while dsBT[t].data != None :
t += 1
dsBT[t].data = x
dsBT[c].RightPointer = t
break
else:
c = dsBT[c].RightPointer
else:
if dsBT[c].LeftPointer == 0:
t = c
while dsBT[t].data != None:
t += 1
dsBT[t].data = x
dsBT[c].LeftPointer = t
break
else:
c = dsBT[c].LeftPointer
**this part is for printing out the data **
dsBT = []
for j in range(2):
dsBT.append(BT( None ,None , None ))
for h in range(len(dsBT)):
#video game name
vgm = input(str("enter the game name:\n"))
insert(vgm)
for i in range(len(dsBT)):
print(dsBT[i].LeftPointer , dsBT[i].data ,dsBT[i].RightPointer)
the error it is showing:
enter the game name:
sarim
enter the game name:
dasr
Traceback (most recent call last):
File "C:\Users\workm\Desktop\Sarim\untitled0.py", line 44, in <module>
insert(vgm)
File "C:\Users\workm\Desktop\Sarim\untitled0.py", line 14, in insert
if dsBT[c].data == None :
TypeError: list indices must be integers or slices, not NoneType
I'm learning to program with python and I came across this issue: I'm trying to make a Guessing Game, and while trying to check for the win condition, the function doesn't recognise the input variable, which I made sure I returned with a previous function. So i get the 'name << 'first_input' is not defined' >> error. I thought it had something to do with the variable not being global or sth like that.
import random
ran_int = random.randint(1,100)
guesses = 0
# here you input the number and it keeps asking unless you do so with 1 to 100
def ask():
first_input = 0
while first_input < 1 or first_input > 100:
first_input = int(input('Enter a number between 1 and 100: '))
return first_input
# this is just to increment the number of guesses stored for showing at the end # of the game
def guesses_inc():
global guesses
guesses += 1
return guesses
# here is where i get the error, as if my ask() function didn't return
# the value properly or as if I assigned it wrongly
def check_win_1():
if first_input == ran_int:
guesses_inc()
print(f'BINGO!\nYou guessed correctly after {guesses} times.')
elif (abs(ran_int - first_input) <= 10):
guesses_inc()
print('WARM!')
ask2()
elif first_input < 1 or first_input > 100:
print('Out of bounds!')
ask2()
else:
guesses_inc()
print('COLD!')
ask2()
ask()
check_win_1()
And here is the error
---------------------------------------------------------------------------
NameError Traceback (most recent call last)
<ipython-input-11-bfd5497995df> in <module>
----> 1 check_win_1()
NameError: name 'first_input' is not defined
I didn't paste the whole code because while testing it it returned the error at this stage so I didn't think the rest mattered for this particular problem. I tried making the var input global and stuff like that but i don't think I did it properly.
Your method call is not correct. You should call your functions like this
def check_win_1(first_input):
if first_input == ran_int:
guesses_inc()
print(f'BINGO!\nYou guessed correctly after {guesses} times.')
elif (abs(ran_int - first_input) <= 10):
guesses_inc()
print('WARM!')
ask2()
elif first_input < 1 or first_input > 100:
print('Out of bounds!')
ask2()
else:
guesses_inc()
print('COLD!')
ask2()
first_input = ask()
check_win_1(first_input)
The error is there because you are trying to use first_input somewhere (i.e. inside check_win_1()).
A possible, not recommended, solution is to qualify your variable as global, which should be used VERY sparingly.
Instead, it is recommended to use function parameters, so as to encapsulate your code in self-contained blocks, e.g.:
def func(a, b):
return a + b
x = func(10, 5)
rather than:
def func():
global a, b
return a + b
a = 10
b = 5
x = func()
For your that may mean doing something like:
def check_win_1(first_input, ran_int):
...
and use them accordingly, e.g.:
first_input = ask()
check_win_1(first_input, ran_int)
etc.
EDIT
Following the above principle, your code could have looked like:
import random
MIN_VAL = 1
MAX_VAL = 100
WARM_LIMIT = 10
def ask_number(
min_val=MIN_VAL,
max_val=MAX_VAL):
guess = None
while guess is None:
guess = int(input(f'Enter a number between {min_val} and {max_val}: '))
if guess < min_val or guess > max_val:
print('Out of bounds!')
guess = None
return guess
def check_guess(
guess,
target,
num_guesses,
warm_limit=WARM_LIMIT):
if guess == target:
print(f'BINGO!\nYou guessed correctly after {num_guesses} times.')
return True
else:
if (abs(guess - target) <= warm_limit):
print('WARM!')
else:
print('COLD!')
return False
# : main
target = random.randint(MIN_VAL, MAX_VAL)
num_guesses = 0
won = False
while not won:
guess = ask_number()
num_guesses += 1
won = check_guess(guess, target, num_guesses)
I'm having quite a hard time creating this program.
Basically the goal is to request user input 7 times, validate the user input based on the criteria of being >= 0 and a valid real number, create a list of that input, then process the input to output Total, max, min, and average.
MAX_HOURS=7
def get_string(prompt):
value=""
value=input(prompt)
return int(value)
def get_pints(pints):
counter = 0
while counter < MAX_HOURS:
pints[counter] = get_real("How many pints were donated? ")
counter = counter + 1
return counter
def valid_real(value):
while True:
try:
value=float(value)
if value >= 0:
return True
else:
print("Please enter a valid number greater than 0! ")
return False
except ValueError:
print("Please enter a valid number greater than 0! ")
return False, int(value)
def get_real(prompt)
value=""
value=input(prompt)
while not valid_real(value):
print(value, "is not a valid entry. Please enter a number greater than 0")
value=input(prompt)
return value
def get_total_pints(pints):
counter = 0
total_pints = 0.0
while counter < 7:
total_pints = total_pints + pints[MAX_HOURS]
counter = counter + 1
return total_pints
def get_min_pints(pints):
min_pints = pints[MAX_HOURS]
min_pints = 0
for i in range(7):
if i < min_pints:
min_pints = i
return min_pints
def get_max_pints(pints):
max_pints = pints
max_pints = 0
for i in range (MAX_HOURS):
if i > max_pints:
max_pints = i
return max_pints
def get_average_pints(total_pints):
average_pints = 0
average_pints=total_pints / MAX_HOURS
return average_pints
def full_program():
pints=[0 for i in range(MAX_HOURS)]
max_pints=[0 for i in range(MAX_HOURS)]
total_pints=[0 for i in range(MAX_HOURS)]
counter=0
pints=get_pints(pints)
total_pints = get_total_pints(pints)
print([pints])
print(int(total_pints))
full_program()
While I'm pretty sure my input validation loop is correct, it seems like the main issue is that I have a an int object that can't be subscripted. I've read other posts and tried some of the code that worked in those scenarios, but I can't get my program to run correctly.
I'm really struggling and at this point, any guidance in the right direction is appreciated.
EDIT: I sent some of the wrong code, I've been revising this code so much I got mixed up on what I meant to send.
Also:
Traceback (most recent call last):
File "C:/Users/User/Desktop/classwork 1125/lab5original.py", line 193, in <module>
full_program()
File "C:/Users/User/Desktop/classwork 1125/lab5original.py", line 182, in full_program
total_pints = get_total_pints(pints)
File "C:/Users/User/Desktop/classwork 1125/lab5original.py", line 97, in get_total_pints
total_pints = total_pints + pints[MAX_HOURS]
TypeError: 'int' object is not subscriptable
So, whenever I call a function that calls another function I get this TypeError and I don't know why because it doesn't happen when I call first function. Here's the code:
def codeChar(c,key):
k = ord(c) + key
if key > 26:
key = key % 26
if 91 <= k <= 96:
k = k - 26
elif 123 <= k:
k = k - 26
c = chr(k)
return c
def codeBlock(word,key):
i = 0
result = ""
while i < len(word):
k = int(key[i])
result = result + codeChar(word[i],k)
i = i + 1
return result
def isletter(h):
i = ord(h)
if 65 <= i <= 90:
return True
elif 97 <= i <= 122:
return True
else:
return False
def codeString(string,key):
i = 0
result = ""
while i < len(string):
k = int(key[i])
if isletter(string[i]) == True:
result = result + codeBlock(string[i],k)
i = i + 1
else:
i = i + 1
return result
print(codeString(input("Enter a sentence to be coded: "),input("Enter an 8 digit key: ")))
The error code received when I run it is this:
Enter a sentence to be coded: Hello world
Enter your student number: 16061226
Traceback (most recent call last):
File "E:\cw.1\cw.1.py", line 89, in <module>
print(codeString(input("Enter a sentence to be coded: "),input("Enter your student number: ")))
File "E:\cw.1\cw.1.py", line 82, in codeString
result = result + codeBlock(string[i],k)
File "E:\cw.1\cw.1.py", line 39, in codeBlock
k = key[i]
TypeError: 'int' object is not subscriptable
Thanks in advance!
When you pass k to codeBlock on line 36, it's an integer, rather than the string that your function is expecting. Perhaps you intended to use key here instead?
It has nothing to do with calling a function from another function. When you call codeBlock from within codeString, you pass it a parameter k, which is an integer. On the other side, with key in the codeBlock function, you try to index into that integer by doing int(key[i]), hence the typeError.