I have a numpy array as follows:
board = np.arange(9).reshape(3, 3)
I would like to replace a value in the array, for example:
board[1, 2] = 'x'.
But as I understand, I cannot do this as the array is in type int and what I am trying to replace it with is a string. When I run this, I get the error:
ValueError: invalid literal for int() with base 10: 'x'
I tried setting the dtype of the array to str:
board = np.arange(9, dtype=str).reshape(3, 3)
But this gives me the error:
ValueError: no fill-function for data-type.
Thanks
In numpy any non-numeric dtype is of type object.
This will work:
board = np.arange(9, dtype=object).reshape(3, 3)
board[1, 2] = 'x'
Cheers.
Related
I have a list of hex values and I need to shift eacgh element by 9 and combine the result with another list. I have provided an example below of what I tried.
x = [hex(10), hex(11)]
y = x[0] << 1
This results in an error:
TypeError: unsupported operand type(s) for <<: 'str' and 'int'
While the below code works as I like but returns an int
x = [0xa, 0xb]
y = x[0] << 1
My question is how can I get the first code example to work?
I understand that the list is returning a string and not an int. I tried to type cast from a str to a hex, but this caused an error. I then tried to type cast from the string to int to hex and received an error for the str to int type cast.
I need to result to be stored as a hex in the list so changing the list to integers would not work for me.
The best way is to use the constructor 'int' with basis 16 to convert the hex values to integers, then use the bitwise operators
a=hex(10)
b=hex(11)
x = [int(a,16),int(b,16)]
y = x[0] << 1
print(x)
print(y)
You can convert hex strings to integers using
int(hex(10), base=16)
but that would just return 10.
If you have a list of integers, I would first shift them the amount you need to shift them by, and then convert them to hexadecimal strings using hex. The value of a hex and its integers are the same, e.g. 0xa == 10 is True. But hex(10) returns a string.
So
nums = [10, 11, ...]
nums = [x << 9 for x in nums]
hex_nums = map(hex, nums)
or something similar.
I have a train dataset which has 43 attributes. Each of the attributes have some tuple values as objects (as in strings with certain characters).
Now, I'm trying to scale the values using a scaler, but it gives the following error:
could not convert string to float: '?'
Now, I don't know how to convert objects to int or float in a single command and converting it for each of the 43 attributes one by one is a bit tedious.
So I want to know how to do it for the complete dataset with a single command.
I use the convert function which tries to parse the string as a float.
If it cannot, it tries to parse it as a int, and if it still cannot, assigns the value 0 (you can change the default value is the string is not a int or a float to something else)
l = []
def convert(str):
x = 0
try:
x = int(str)
except:
try:
x = float(str)
except:
pass
l.append(x)
for i in ['1','2','3','?','4.5']:
convert(i)
print(l)
#[1, 2, 3, 0, 4.5]
counter = 0
for i in len(s):
if i in ('a','e','i','o','u'):
counter += 1
print("Number of vowels:" + str(counter))
I'm trying to make a program that counts the number of vowels assuming that s is a string that is predefined. But I'm getting an error:
'int' object is not iterable error in python
I'll make my answer a bit longer than it should be.
If you don't need a numerical representation i of your index for operations within your loop, you just iterate over the string:
for i in s:
do_something()
If you only need a numerical representation i, e.g. you have a 'string', but you need [0,1,2,3,4,5], you can do this:
for i in range(len(s)):
do_something(i)
Let's break it down. s is a str(). len returns the length of an object as an integer value, for example, len('string') = 6. You can't iterate over an integer, because python's for is actually a foreach. So you need an iterable object, which is range(len(s))
If you need both the symbol and the index, you can do this:
for i, symbol in enumerate(s):
do_something(i,symbol)
For example, this snippet of code:
for i, symbol in enumerate('string'):
print(i,symbol)
Will result in:
0 s
1 t
2 r
3 i
4 n
5 g
len() returns type int as length of the string s in your case.
Use for i in s: as #Patrick Artner suggested.
Alternatively you can use
for i in range(len(s)):
curChar=s[i]
Im using python 3 to create a list of random dice rolls and add them up, however when i try to add all the totals it gives me TypeError: unsupported operand type(s) for +: 'int' and 'list. What to do?
count = 0
lista=[[] for q in range(5)]
while count<len(lista):
import random
c=random.randrange(1,7,1)
lista[count].append(c)
count += 1
print(lista)
total=sum(lista)
Hi You are trying to add int value to list So, Type mismatch error,
You have to try to add int value with list value
count = 0
total = 0
lista=[[]for q in range(5)]
while count<len(lista):
import random
c=random.randrange(1,7,1)
lista[count].append(c)
total += lista[count][0]
count += 1
print(lista)
print total
No offence, but oh my god, that is so unpythonistic that my eyes bleed. But obviously you have to start somewhere ;)
I guess you have done C development previously. In Python you don't need to preallocate memory or arrays. You also can iterate over any iterable directly, no need to use an increasing integer index.
Just do:
import random
lista = [random.randrange(1, 7, 1) for q in range(5)]
print(lista)
total = sum(lista)
This will create lista as a list of five integers returned by random.randrange().
Your problem is: when you do lista=[[] for q in range(5)], you get a list of 5 empty lists ([[], [], [], [], []]). Then when you lista[count].append(c) you end up with a list of list containing an integer each ([[5], [1], [3], [4], [3]]). sum will then try to sum the inner lists, not the integers. That fails.
I want to use a variable as an argument for count = Counter(list).most_common(x). But receive this error:
TypeError: unorderable types: str() >= int()
My code works fine when there is a constant in place for x like: count = Counter(list).most_common(2)
Any help would be appreciated.
Thanks