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'
Related
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
I'm new to python I'm trying to implement a code for my project at first my error code was object of type 'int' has no len() this was my code and added str to solve the issue
xored_value = ord(Mblocks[i%len(Mblocks)]) ^ ord(Cblocks[i%len(Cblocks)])
Now I'm getting 'int' object is not subscriptable if in this line
xored_value = ord(Mblocks[i%len(str(Mblocks))]) ^ ord(Cblocks[i%len(str(Cblocks))])
If I change it to
xored_value = ord(Mblocks(i%len(str(Mblocks)))=)) ^ ord(Cblocks(i%len(str(Cblocks))))
I get 'str' object is not callable.
Here's my full function :
def xor_two_str(Mblocks,Cblocks):
xored = []
for i in range(max(len(str(Mblocks)), len(str(Cblocks)))):
xored_value = ord(Mblocks[i%len(str(Mblocks))]) ^ ord(Cblocks[i%len(str(Cblocks))])
xored.append(hex(xored_value)[2:])
return ''.join(xored)
Any help please?
So, I am sure the Mblocks and Cblocks parameters you are passing are integers. Since it is being an integer, if you try to slice part of it you will get TypeError
> 100[1]
TypeError: 'int' object is not subscriptable
Lets do a piece by piece inspection.
Here in the first approach:
> xored_value = ord(Mblocks[i%len(Mblocks)]) ^ ord(Cblocks[i%len(Cblocks)])
> error1 = len(Mblocks)
TypeError: object of type 'int' has no len()
since Mblocks is integer, integer doesn't have len function
In change 2,
you corrected the first error but:
> xored_value = ord(Mblocks[i%len(str(Mblocks))]) ^ ord(Cblocks[i%len(str(Cblocks))])
> error2 = Mblocks[i%len(str(Mblocks))]
> error2 = Mblocks[some_int]
TypeError: 'int' object is not subscriptable
In change 3:
xored_value = ord(Mblocks(i%len(str(Mblocks)))=)) ^ ord(Cblocks(i%len(str(Cblocks))))
> error3 = Mblocks(callingWithParameter)
Simply in python something(withbraces) is calling something. Same happened here
So the easiest solution is make Mbraces and Cbraces of before you process anything down Like here is the solution:
def xor_two_str(Mblocks,Cblocks):
Mblocks = str(Mblocks)
Cblocks = str(Cblocks)
xored = []
for i in range(max(len(Mblocks), len(Cblocks))):
xored_value = ord(Mblocks[i%len(Mblocks)]) ^ ord(Cblocks[i%len(Cblocks)])
xored.append(hex(xored_value)[2:])
return ''.join(xored)
Python expects strings for the ord() function, and this:
Mblocks[i%len(str(Mblocks))]
is an attempt to access element with index i%len(str(Mblocks)) from int Mblocks, which Python does not allow.
As such, you could do a str conversion at the beginning of your function and work with the converted variables from that point onwards.
def xor_two_str(Mblocks,Cblocks):
str_Mblocks=str(Mblocks)
str_Cblocks=str(Cblocks)
xored =[]
for i in range(max(len(str_Mblocks), len(str_Cblocks))):
xored_value = ord(str_Mblocks[i%len(str_Mblocks)]) ^ ord(str_Cblocks[i%len(str_Cblocks)])
xored.append(hex(xored_value)[2:])
return ''.join(xored)
When I print a numpy.timedelta64 scalar using string formatting I get a TypeError.
In [10]: td = np.timedelta64(5410102,'us')
In [12]: td.ndim # check td is really a scalar
Out[12]: 0
In [13]: print("td: {}".format(td))
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-13-bae2acf5773a> in <module>
----> 1 print("td: {}".format(td))
TypeError: int() argument must be a string, a bytes-like object or a number, not 'datetime.timedelta'
In [14]: print("td: {!r}".format(td)) # printing using repr() works as expected
td: numpy.timedelta64(5410102,'us')
In [15]: print(td) # Just printing also works fine
5410102 microseconds
Any ideas what's going on?
Update:
The error seems to be in the numpy.timedelta64.__format__() function.
In [67]: td.__format__("")
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-67-6acc460ea008> in <module>
----> 1 td.__format__("")
TypeError: int() argument must be a string, a bytes-like object or a number, not 'datetime.timedelta'
It just seems a bug to me. A work around is to convert it to string before formatting.
In [68]: print("{}".format(str(td)))
5410102 microseconds
You can read about datetime.timedelta function here. Anyways, it says that this function return an instance of a Date object.
The error appears because you can't concatenate a string with an object.
In order to solve this problem, you need to concatenate the string with a printable representation of the object using one of the follwing ways:
print(str + str(object)) # In this case, turns to the toString() function of the object, if exists (otherwise it returns an error). Converts the text the object shows to a string. In this case, it's possible to use that method on Date instances.
print(str + repr(object) # repr() functions returns a printable representation of the object of their class.
By the way, the line print(object) works because it turns to the toString() function of the object. Using print(str + object) is forbidden because it tries to print a non-concatenative variables which is not possible, as explained.
Line 84 in lstToDt() method, I tried to convert 'i' which takes a string datetime from list to datetime object but:
when I use datetime.datetime.strftime(i,"format") an error comes that i is a string object and not datetime.datetime.
When I use datetime.datetime.strptime(i,"format") an error comes that i is a datetime.datetime and not string.
Code :
def lstToDt(lt): # Converts list string elements into Dates
for i in lt:
i = datetime.datetime.strftime(i,"%Y-%m-%d")
lt.append(datetime.datetime.strptime(i,"%Y-%m-%d"))
return lt
Errors :
i = datetime.datetime.strftime(i,"%Y-%m-%d")
TypeError: descriptor 'strftime' requires a 'datetime.date' object but received a 'str'
lt.append(datetime.datetime.strptime(i,"%Y-%m-%d"))
TypeError: strptime() argument 1 must be str, not datetime.datetime
What is happening? Can anyone help please?
You have passed string value to strptime, that is not acceptable for python,
def lstToDt(lt): # Converts list string elements into Dates
for i in lt:
j = datetime.datetime.strptime(i,"%Y-%m-%d")
lt.append(datetime.datetime.strptime(j,"%Y-%m-%d"))
return lt
This should work!
Hope this helps!
I'm trying to do a type check with an element of a pandas dataframe which appears to be a string:
type(atmdf.ix[row]['bid'])
<type 'str'>
however, if I do a type check I get False:
type(atmdf.ix[row]['bid']) is 'str'
False
even with the isinstance I get the same unexpected result:
isinstance(type(atmdf.ix[row]['bid']), str)
False
where am I wrong?
P.S. the content of the dataframe is something like this:
atmdf.ix[row]['bid']
'28.5'
thank you!
You have to test the string itself with isintance, not the type:
In [2]: isinstance('string', str)
Out[2]: True
So in your case (leaving out the type(..)): isinstance(atmdf.ix[row]['bid'], str).
Your first check did not work because you have to compare to str (the type) not 'str' (a string).