Struggling to convert a float 12345678.0 to a string 12345678 Gone through a few different solutions I've found in SO, but can't seem to get to the finish line, the decimal point will not drop.
Here is what I've tried
df["variable"]= df["variable"].astype(str)
df["variable"]= df["variable"].astype(int).astype(str)
# old lambda solution
cols = ['variable']
for col in cols:
df[col] = df[col].apply(lambda x: int(x) if x == x else "")
# convert int to string
df["variable"] = df["variable"].astype(str)
You can do it simply like this:
df['variable'] = df['variable'].astype(int, errors = 'ignore').astype(str)
Here's your lambda function
lambda x: str(int(x))
Related
The task is:
User enters a number, you take 1 number from the left, one from the right and sum it. Then you take the rest of this number and sum every digit in it. then you get two answers. You have to sort them from biggest to lowest and make them into a one solid number. I solved it, but i don't like how it looks like. i mean the task is pretty simple but my code looks like trash. Maybe i should use some more built-in functions and libraries. If so, could you please advise me some? Thank you
a = int(input())
b = [int(i) for i in str(a)]
closesum = 0
d = []
e = ""
farsum = b[0] + b[-1]
print(farsum)
b.pop(0)
b.pop(-1)
print(b)
for i in b:
closesum += i
print(closesum)
d.append(int(closesum))
d.append(int(farsum))
print(d)
for i in sorted(d, reverse = True):
e += str(i)
print(int(e))
input()
You can use reduce
from functools import reduce
a = [0,1,2,3,4,5,6,7,8,9]
print(reduce(lambda x, y: x + y, a))
# 45
and you can just pass in a shortened list instead of poping elements: b[1:-1]
The first two lines:
str_input = input() # input will always read strings
num_list = [int(i) for i in str_input]
the for loop at the end is useless and there is no need to sort only 2 elements. You can just use a simple if..else condition to print what you want.
You don't need a loop to sum a slice of a list. You can also use join to concatenate a list of strings without looping. This implementation converts to string before sorting (the result would be the same). You could convert to string after sorting using map(str,...)
farsum = b[0] + b[-1]
closesum = sum(b[1:-2])
"".join(sorted((str(farsum),str(closesum)),reverse=True))
I have a dataset which has values of players given as a string. Values of few players are in millions while others are in thousands. I want to convert all these into float from string with values in millions.
Tried to iterate through the rows while checking if 'K' representing thousand is there or not and if it is then divide it by 1000 to convert it into million.
for x in dataset['Value'].tolist():
s = pd.Series(x)
if 'K' in s:
x = x.map(lambda x: str(x)[:-1])
x = x.map(lambda x: str(x)[1:])
x = pd.to_numeric(x)
x = x/1000
else:
x = x.map(lambda x: str(x)[:-1])
x = x.map(lambda x: str(x)[1:])
x = pd.to_numeric(x)
'str' object has no attribute 'map'.
Why not just
def to_millions(s):
if s.endswith('K'):
return float(s.rstrip('K')) / 1000.0
else:
return float(s)
Note: float is a poor representation of monetary values, unless all you do is rough estimates. Real finance applications use Decimal.
Re the use of .map: I have no idea either what the code tried to achieve.
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]
Is there other ways to convert a string to int in python2 without int and string.atoi? Like convert a "2" to 2.
>>> a="2"
>>> int(a)
2
>>>
I would recommend using try catch,
try:
a = int(a)
except:
#do something
You can also use ast module,
>>> import ast
>>> ast.literal_eval("2")
2
>>>
You can also try a more "esoteric" solution like this!
def ascii_to_int(number):
value = 0
multiplier = 1
for n in reversed(number):
value += (ord(n)-48)*multiplier
multiplier *= 10
return value
result_value = ascii_to_int('123')
print result_value, type(result_value)
the output is
123 <type 'int'>
you can convert string to Int without any standard function (using an algorithm)... just follow this little tutorial : www.youtube.com/watch?v=HIJ289o6hxY
I'm trying to get toBase10(101) to spit out 5. I also need it to work for numbers besides 101, I know that there is a binary converter built into python but I can't figure it out.
Right now I have
def toBase10(x):
int( 'x' , 2 ) == x
return x
I get the error can't convert non-string with explicit base. Why can't I use x in here?
def toBase10(x):
return int(x, 2)
I converted the integer into a string and then into binary with which I could easily convert into an integer:
def binaryconvert(x):
x = str(x)
binarynumber = int(x, base=2)
convertnumber = int(binarynumber)
return convertnumber
print(binaryconvert(101))
#the answer would be 5
There's also another way if your input is already binary:
def binaryconvert(x):
convertnumber = int(x)
return convertnumber
x = int(input("Input: "),2)
print(binaryconvert(x))
try
def toBase10(item):
return int(str(item),2)
then you can pass either string or int
print toBase10(101)
print toBase10('101')
i think the int cast error is because you are passing in a number not a string, although this looks odd --> "int( x , 2 ) == x" too