How can i convert below code to int from object in python? - python

I have been trying to change an object to string, so i first did the below code
total_deliveries_data.Order_ID = map(lambda x : x.str.split('-').str[1].str.split(',').str[0], total_deliveries_data.Order_ID)
total_deliveries_data
when i try the below code to convert the column to in.
total_deliveries_data["Order_ID"] = total_deliveries_data["Order_ID"].astype(str).astype(int)
i get
ValueError: invalid literal for int() with base 10: '<map object at 0x7f9f1f678f10>'
How can i sort this out

Related

ValueError: could not convert string to float: '1.318.21''

i'm trying to convert data type from object to float, however when I try to convert it shows the error message:
ValueError: could not convert string to float: '1.318.21'
Here is the code:
profkes_na=profkes_df.fillna(0)
profkes_decimal=profkes_na.stack().str.replace(',','.').unstack()
profkes_float=profkes_decimal.astype('float')
Thank you.
change : profkes_decimal=profkes_na.stack().str.replace(',','.').unstack()
to : profkes_decimal=profkes_na.stack().str.replace(',','').unstack()
It's unclear from the question what modules are being used. In pure Python one could do this:
s = '1.318.21'
def asfloat(s):
if (ndp := s.count('.')) > 1:
s = s.replace('.', '', ndp-1)
return float(s)
print(asfloat(s))

ValueError: invalid literal for int() with base 16

I have a problem with conversion from string to an integer.
I have function which return variable a = 00007fff`90492630. This variable has type Unicode. This is the address of the function that I will use to install breakpoints via pykd (plugin for windbg).
At the next function, I would like to convert this variable to int, using int(a,16).
But i have this error:
ValueError: invalid literal for int() with base 16: '00007fff`90492630'
Thanks for your help!
If you need to remove the tick in the code, you can do :
a = '00007fff`90492630'
b = int(a.translate(str.maketrans({'`':""})), 16)
print(b)
You got a single quote\tick inside your string.
When deleting it, you got the following output :
>>> int("00007fff90492630", 16)
140735614101040
Try to use pykd.expr it converts any windbg constant / symbols / expression to 64 bit long value
If you want to get offset of a function, use pykd.getOffset(func_name) instead of dbgCommand('x ' + func_name )

How to automatically determine type for user input?

I want to make a simple math function that takes user input, yet allows the user to not input an integer/float. I quickly learned Python does not identify type by default. Quick Google search shows using literal_eval, but it returns with ValueError: malformed string if a string is the input. This is what I have so far:
from ast import literal_eval
def distance_from_zero(x):
if type(x) == int or type(x) == float:
return abs(x)
else:
return "Not possible"
x = literal_eval(raw_input("Please try to enter a number "))
print distance_from_zero(x)
Just answer your query why ValueError: malformed string occurred if you read the literal_eval doc :
Safely evaluate an expression node or a string containing a Python
expression. The string or node provided may only consist of the
following Python literal structures: strings, numbers, tuples, lists,
dicts, booleans, and None.
so string should be inclosed by "" as used to write in editor like s = "string"
raw_input takes the input and convert to string data type so i have tried this and able to convert using literal_eval
>>> x=raw_input()
string
>>> x= "\""+x+"\"" # concatenating the "" to string
>>> literal_eval(x)
'string'
>>>
Like you mentioned you will get malformed string error (ValueError) if you get input like ast.literal_eval('c1'). You will also get SyntaxError if you do something like ast.literal_eval('1c'). You will want get the input data and then pass it to literal_eval. You can then catch both of these exceptions, and then return your 'Not Possible'.
from ast import literal_eval
def distance_from_zero(x):
try:
return abs(literal_eval(x))
except (SyntaxError, ValueError):
return 'Not possible'
x = raw_input("Please try to enter a number ")
print distance_from_zero(x)

How to insert np.array object in pandas.Series?

Given the following pandas series:
s = pd.Series(dict(A = np.zeros(100), B = np.zeros(100), C = None))
How can I replace the last element with the object np.zeros(100)? In the real case, I have a very long Series and want to replace all None objects in a similar way.
So far, I tried:
s.fillna(np.zeros(100))
ValueError: invalid fill value with a <type 'numpy.ndarray'>
s.replace(None, np.zeros(100))
TypeError: 'regex' must be a string or a compiled regular expression or a list or dict of strings or regular expressions, you passed a 'bool'
s.fillna(np.NaN).replace(np.NaN, np.zeros(100))
TypeError: Invalid "to_replace" type: 'float'

Conversion From String To Int

I'm communicating with a modem via COM port to recieve CSQ values.
response = ser.readline()
csq = response[6:8]
print type(csq)
returns the following:
<type 'str'> and csq is a string with a value from 10-20
For further calculation I try to convert "csq" into an integer, but
i=int(csq)
returns following error:
invalid literal for int() with base 10: ''
A slightly more pythonic way:
i = int(csq) if csq else None
Your error message shows that you are trying to convert an empty string into an int which would cause problems.
Wrap your code in an if statement to check for empty strings:
if csq:
i = int(csq)
else:
i = None
Note that empty objects (empty lists, tuples, sets, strings etc) evaluate to False in Python.
As alternative you can put your code inside an try-except-block:
try:
i = int(csq)
except:
# some magic e.g.
i = False

Categories