Why its Showing None when it should show Which IP Class it belongs to - python-3.x

import pandas as pd
ecom = pd.read_csv("data science pack\Ecommerce Purchases.csv")
ecom['Class_IP'] = ecom['IP Address'].apply(lambda x:x.split(".")[0])
def ipc(x):
if x in range(0,128):
print("A")
if x in range(128,192):
print("B")
if x in range(192,224):
print('C')
if x in range(224,240):
print("D")
if x in range(240,255):
print("E")
ecom['new_c'] = ecom['Class_IP'].apply(lambda y : ipc(y))
print(ecom['new_c'])
Above is the code. It should print it IP class but it shows None values.

can you please try to pass int(y) instead of y to ipc() method in lambda function as below:
ecom['new_c'] = ecom['Class_IP'].apply(lambda y : ipc(int(y)))
It is returning None because ipc function is expecting int value and you are passing string value to it.
Hope this answer solves your problem.

Related

Why error: "must be real number, not RestMode"? How can fix it?

I'm using ROS, and writing some codes to do some tasks, and now I'm facing an error: TypeError: must be real number, not RestMode, for more details, I have code here:
#!/usr/bin/env python
#encoding: utf-8
import rospy
from geometry_msgs.msg import Vector3
from sensor_msgs.msg import Imu
from std_msgs.msg import Float64
import numpy as np
import geometry as geo
import transformation as tf
from IK_solver import IK
class RestMode:
def __init__(self, bodyDimensions, legDimensions):
# rospy.Subscriber('spot_keyboard/body_pose',Vector3,self.callback)
self.bodyLength = bodyDimensions[0]
self.bodyWidth = bodyDimensions[1]
self.bodyHeight = bodyDimensions[2]
self.l1 = legDimensions[0]
self.l2 = legDimensions[1]
self.l3 = legDimensions[2]
# rospy.Subscriber('spot_imu/base_link_orientation',Imu, self.get_body_pose)
self.rate = rospy.Rate(10.0) #10Hz
self.rb = IK(bodyDimensions, legDimensions)
angles_cmd = [ 'spot_controller/FL1_joint/command',
'spot_controller/FL2_joint/command',
'spot_controller/FL3_joint/command',
'spot_controller/RL1_joint/command',
'spot_controller/RL2_joint/command',
'spot_controller/RL3_joint/command',
'spot_controller/RR1_joint/command',
'spot_controller/RR2_joint/command',
'spot_controller/RR3_joint/command',
'spot_controller/FL1_joint/command',
'spot_controller/FL2_joint/command',
'spot_controller/FL3_joint/command' ]
self.joint = []
for i in range(12):
self.joint.append(rospy.Publisher(angles_cmd[i], Float64, queue_size=10))
# self.initial_pose()
def initial_pose(self,roll=0,pitch=0,yaw=0,dx=0,dy=0,dz=None):
if dz == None:
dz = self.bodyHeight
order = ['FL','RL','RR','FR']
angles = []
rospy.loginfo("Start Calculate Angles!")
for leg in order:
(q1,q2,q3,ht) = self.rb.calculateAngles(self,roll,pitch,yaw,dx,dy,dz,leg)
angles.append(q1)
angles.append(q2)
angles.append(q3)
rospy.loginfo("Done! Start publish!")
for i in range(12):
self.joint[i].publish(angles[i])
self.rate.sleep()
if __name__ == '__main__':
rospy.init_node('rest_mode', anonymous=True)
body = [0.1908, 0.080, 0.15]
legs = [0.04, 0.1, 0.094333]
rest = RestMode(body, legs)
try:
while not rospy.is_shutdown():
rest.initial_pose()
except rospy.ROSInterruptException:
pass
When method calculateAngles(self,roll,pitch,yaw,dx,dy,dz,leg) with argument leg in last, it throws: TypeError: must be real number, not RestMode.
But when I change it to first like: calculateAngles(self,leg,roll,pitch,yaw,dx,dy,dz), then error says: TypeError: must be real number, not str with input in another module, but I tested all of the others related module, and they are fine, so I think that must be an issue in codes above!
That error is so strange:
I don't push any str as input
When changing the position of argument leg, it throws a different error.
When calling instance methods, self is an implied parameter, and should never be explicitly passed. When you are using self.rb.calculateAngles(self, ..., that second self is an instance of a RestMode class, which your IK class does not accept...
Therefore, you want
(q1,q2,q3,ht) = self.rb.calculateAngles(roll,pitch,yaw,dx,dy,dz,leg)
And change other usages within the IK class as well

Type warning Pycharm

Given the following example:
class A:
def __init__(self, x: (float, np.ndarray) = 0.05):
self.x = x
what i intend with it is to give a hint to the user that the argument x can be a float or a numpy array. If nothing is given, set default to 0.05. Is this the right use ? If yes, why does Pycharm warm when i initiate A as follows ? :
a = A(x=np.random.rand(3, 3)) #Expected type 'float', got 'ndarray' instead
If its not the right use, where is my thinking wrong? Doesnt x:(float,np.ndarray) mean that x can be a float or np.ndarray?
Use Union:
from typing import Union
class A:
def __init__(self, x: Union[float, np.ndarray] = 0.05):
self.x = x

OOP, adding a returned variable from a method in to parenthesis of another method

I have the following script. I have returned variable called minima from a method (i.e max_Impact). I want to use that variable along with other variables including self in another method (i.e netloss). However, when I do, I get an error called "name self is not defined". If I were to remove self (i.e def netloss(self,lim1 = 0, lim2 = minima): ). Then I get an error called "name minima is not defined". Any ideas about how to solve this issue.
Note, I am referring to the last 2 methods, I have added some of the other function for just reference.
#Imports
import numpy as np
from scipy.signal import argrelextrema
from scipy import optimize
from scipy import integrate
# Function just for reference
def polynomial_eq2(x):
p4eq = lambda x: clf4.intercept_[0] + clf4.coef_[0][1] * x + clf4.coef_[0][2]*np.power(x,2) + clf4.coef_[0][3]*np.power(x,3) + clf4.coef_[0][4]*np.power(x,4)
return integrate.quad(p4eq,lim1,lim2)
class ImpRec():
def __init__(self,X,Y):
self.X = X
self.Y = Y
self.minima_index = argrelextrema(self.Y,np.less)
self.maxima_index = argrelextrema(self.Y,np.greater)
self.approx_converge_pt = []
self.approx_converge_idx = []
#Calculates local minima
def max_impact(self):
self.minima = self.Y[self.minima_index] #self.minima
return (self.minima)
..... #bunch of other methods
def netloss(self,lim1 = 0, lim2 = self.minima):
sol_netloss = integrate.quad(polynomial_eq2,self.lim1,self.lim2)
return (sol_netloss)
Change this
def netloss(self,lim1 = 0):
lim2 = self.minima
sol_netloss = integrate.quad(polynomial_eq2,self.lim1,lim2)
return (sol_netloss)
and you have to call max_impact before call the netloss.otherwise self.minima is not available

Finding conditional mutual information from 3 discrete variable

I am trying to find conditional mutual information between three discrete random variable using pyitlib package for python with the help of the formula:
I(X;Y|Z)=H(X|Z)+H(Y|Z)-H(X,Y|Z)
The expected Conditional Mutual information value is= 0.011
My 1st code:
import numpy as np
from pyitlib import discrete_random_variable as drv
X=[0,1,1,0,1,0,1,0,0,1,0,0]
Y=[0,1,1,0,0,0,1,0,0,1,1,0]
Z=[1,0,0,1,1,0,0,1,1,0,0,1]
a=drv.entropy_conditional(X,Z)
##print(a)
b=drv.entropy_conditional(Y,Z)
##print(b)
c=drv.entropy_conditional(X,Y,Z)
##print(c)
p=a+b-c
print(p)
The answer i am getting here is=0.4632245116328402
My 2nd code:
import numpy as np
from pyitlib import discrete_random_variable as drv
X=[0,1,1,0,1,0,1,0,0,1,0,0]
Y=[0,1,1,0,0,0,1,0,0,1,1,0]
Z=[1,0,0,1,1,0,0,1,1,0,0,1]
a=drv.information_mutual_conditional(X,Y,Z)
print(a)
The answer i am getting here is=0.1583445441575102
While the expected result is=0.011
Can anybody help? I am in big trouble right now. Any kind of help will be appreciable.
Thanks in advance.
I think that the library function entropy_conditional(x,y,z) has some errors. I also test my samples, the same problem happens.
however, the function entropy_conditional with two variables is ok.
So I code my entropy_conditional(x,y,z) as entropy(x,y,z), the results is correct.
the code may be not beautiful.
def gen_dict(x):
dict_z = {}
for key in x:
dict_z[key] = dict_z.get(key, 0) + 1
return dict_z
def entropy(x,y,z):
x = np.array([x,y,z]).T
x = x[x[:,-1].argsort()] # sorted by the last column
w = x[:,-3]
y = x[:,-2]
z = x[:,-1]
# dict_w = gen_dict(w)
# dict_y = gen_dict(y)
dict_z = gen_dict(z)
list_z = [dict_z[i] for i in set(z)]
p_z = np.array(list_z)/sum(list_z)
pos = 0
ent = 0
for i in range(len(list_z)):
w = x[pos:pos+list_z[i],-3]
y = x[pos:pos+list_z[i],-2]
z = x[pos:pos+list_z[i],-1]
pos += list_z[i]
list_wy = np.zeros((len(set(w)),len(set(y))), dtype = float , order ="C")
list_w = list(set(w))
list_y = list(set(y))
for j in range(len(w)):
pos_w = list_w.index(w[j])
pos_y = list_y.index(y[j])
list_wy[pos_w,pos_y] += 1
#print(pos_w)
#print(pos_y)
list_p = list_wy.flatten()
list_p = np.array([k for k in list_p if k>0]/sum(list_p))
ent_t = 0
for j in list_p:
ent_t += -j * math.log2(j)
#print(ent_t)
ent += p_z[i]* ent_t
return ent
X=[0,1,1,0,1,0,1,0,0,1,0,0]
Y=[0,1,1,0,0,0,1,0,0,1,1,0]
Z=[1,0,0,1,1,0,0,1,1,0,0,1]
a=drv.entropy_conditional(X,Z)
##print(a)
b=drv.entropy_conditional(Y,Z)
c = entropy(X, Y, Z)
p=a+b-c
print(p)
0.15834454415751043
Based on the definitions of conditional entropy, calculating in bits (i.e. base 2) I obtain H(X|Z)=0.784159, H(Y|Z)=0.325011, H(X,Y|Z) = 0.950826. Based on the definition of conditional mutual information you provide above, I obtain I(X;Y|Z)=H(X|Z)+H(Y|Z)-H(X,Y|Z)= 0.158344. Noting that pyitlib uses base 2 by default, drv.information_mutual_conditional(X,Y,Z) appears to be computing the correct result.
Note that your use of drv.entropy_conditional(X,Y,Z) in your first example to compute conditional entropy is incorrect, you can however use drv.entropy_conditional(XY,Z), where XY is a 1D array representing the joint observations about X and Y, for example XY = [2*xy[0] + xy[1] for xy in zip(X,Y)].

How do I use composite strategies in hypothesis (hypothesis.errors.InvalidArgument: Expected SearchStrategy but got function)

This example is a variation of the one in the docs:
import hypothesis.strategies as st
from hypothesis import given
#st.composite
def s(draw):
x = draw(st.text(), min_size=1)
y = draw(st.text(alphabet=x))
return (x, y)
#given(s1=s, s2=s)
def test_subtraction(s1, s2):
print(s1, s2)
assert 0
It fails:
E hypothesis.errors.InvalidArgument: Expected SearchStrategy but got <function accept.<locals>.s at 0x7fd7e5c05620> (type=function)
/mnt/work/unfuncat/software/anaconda/lib/python3.6/site-packages/hypothesis/internal/validation.py:40: InvalidArgument
What am I doing wrong?
You need to call the composite functions. This is not explained in the docs, but there is an example in a 2016 blog post.
#given(s1=s(), s2=s()) # <===== change
def test_subtraction(s1, s2):
print(s1, s2)
assert 0

Resources