Im currently working on an assignment but have encountered a problem. How do I convert a numpy.float64 to integer.
import numpy as np
bike = np.loadtxt('Bike.txt')
def count_days(year, month, day):
year_2011=[31,28,31,30,31,30,31,31,30,31,30,31]
year_2012=[31,29,31,30,31,30,31,31,30,31,30,31]
if (year == 2011):
days= sum(year_2011[:(month-1)])+day
else:
days= 365+sum(year_2012[:month-1])+day
return days
bike_2011 = bike[count_days(2011, 0, 0)-1]
bike_2012 = bike[count_days(2012, 0, 0)-1]
int(bike_2011)
int(bike_2012)
for e in len(bike_2012):
if bike[e] > 8000 : print (bike [e], x)
This returns the following error.
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-25-f111e601c474> in <module>
1 bike_2012.astype(int)
----> 2 for e in len(bike_2012):
3 if bike[e] > 8000 : print (bike [e], x)
TypeError: object of type 'numpy.float64' has no len()
Replacing bike = np.loadtxt('Bike.txt') with bike = np.loadtxt('Bike.txt').astype(int) should do the trick. And while you're at it, you should delete int(bike_2011) and int(bike_2012) -- these do absolutely nothing.
On the other hand, you program has more severe problems, count_days returns a single number, so bike_2011 and bike_2012 are a plain variables, not lists or tuples, so trying to do len(bike_2011) will give you the same error, no matter if bike_2011 is integer or float. You cannot take a length of a float (or integer).
Related
I'm trying to convert Rs. 2,92,667 to integer type but I'm confused like how to remove Rs. and commas from it .
cars = [int(x.split('Rs. ')[-1]) for x in cars['Ex-Showroom_Price']]
---------------------------------------------------------------------------
ValueError Traceback (most recent call last)
<ipython-input-14-b9318b3d5174> in <module>
----> 1 cars = [int(x.split('Rs. ')[-1]) for x in cars['Ex-Showroom_Price']]
<ipython-input-14-b9318b3d5174> in <listcomp>(.0)
----> 1 cars = [int(x.split('Rs. ')[-1]) for x in cars['Ex-Showroom_Price']]
ValueError: invalid literal for int() with base 10: '2,92,667'
This is what I tried
Split the string and remove commas from the numeric part.
rs_string = 'Rs. 2,92,667'
rs_integer = int(rs_string.split()[-1].replace(',',''))
print(rs_integer)
Output:
292667
Note:
This will also work for a string that does not contain the 'Rs.' preamble but does assume that the resulting values can be converted to int. Just replace the call to int with float if required
Thanks to those who give me a solution earlier on.
However i need to utilise the split function for the solution as its part of the requirement stated. When i run this code, there is an error
TypeError Traceback (most recent call last)
in
7
8 for x in dob_list:
----> 9 age +=[year-int(x.split("-")[-1:])]
10 print(age)
TypeError: int() argument must be a string, a bytes-like object or a number, not 'list'
dob_list = ['01-Jan-1990', '11-Aug-1995', '15-Apr-1982', '20-Mar-1988', '25-Nov-1976', '07-Dec-1965',
'18-Dec-1977', '25-May-1994', '09-Oct-1981', '19-Feb-1981']
year = 2021
age =[]
dob = []
for x in dob_list:
age +=[year-int(x.split("-")[-1:])]
print(age)
x.split("-")[-1:] actually gives you a list which contains only the last list item, since you are using a range (like [-1:]) instead of a number (like [-1]).
x.split("-")[-1]gives you the last list item (from x.split("-")) as a string.
The number one debug tool in python is print. A line is failing? Print the stuff on the line before to see what you get.
dob_list = ['01-Jan-1990', '11-Aug-1995', '15-Apr-1982', '20-Mar-1988', '25-Nov-1976', '07-Dec-1965',
'18-Dec-1977', '25-May-1994', '09-Oct-1981', '19-Feb-1981']
year = 2021
age =[]
dob = []
for x in dob_list:
print("next value", repr(x.split("-")[-1:]))
age +=[year-int(x.split("-")[-1:])]
Running, I get
$ python3 test.py
next value ['1990']
Traceback (most recent call last):
File "/home/td/tmp/j/i.py", line 12, in <module>
age +=[year-int(x.split("-")[-1:])]
TypeError: int() argument must be a string, a bytes-like object or a number, not 'list'
That traceback is useful. I see the failing line and it tells me int() doesn't like lists. Looking backwards... yep, that was a list being passed in. Just get the final value instead.
age +=[year-int(x.split("-")[-1])]
I am trying to create a function that returns data starting from a given year and given month to today's year and month. For simplicity I have replaced what I want my function to do with print statements of outer loop and inner loop. I am getting error TypeError: 'str' object cannot be interpreted as an integer
Defining function
def frequency_database(df,start_month,start_year):
data = pd.DataFrame([])
import datetime
start_month=int(start_month)
start_year=int(start_year)
today = datetime.date.today()
today_year=today.strftime('%Y')
for y in range(start_year,today_year):
print('Outer loop enter for year', y)
Some function here which I want to do.............
for x in range(start_month,13):
print('Inner loop enter for month number',x)
Some function here which I want to do.............
Calling funtion
frequency_database(df,1,2015)
Error
TypeError: 'str' object cannot be interpreted as an integer
Stack Trace as requested
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-37-06567ae5d027> in <module>
12 print('Inner loop enter for month number',x)
13
---> 14 frequency_database(df,1,2015)
<ipython-input-37-06567ae5d027> in frequency_database(df, start_month, start_year)
7 today_year=today.strftime('%Y')
8
----> 9 for y in range(start_year,today_year):
10 print('Outer loop enter for year', y)
11 for x in range(start_month,13):
TypeError: 'str' object cannot be interpreted as an integer
The problem is you tried to give range a str which is today_year=today.strftime('%Y').
Just replace the line
today_year=today.strftime('%Y')
with
today_year=int(today.strftime('%Y'))
As pointed out by Stargazer, you could do,
today_year = today.year
instead of converting the str to int
I am trying to run the following code over a CSV file, but the code is showing an error that the input data type should be a str and not an int, but I have checked the data type and it is a float. I have tried every conversion from string, to float, to int, but nothing seems to work. please tell me what am I doing wrong.
print(stdized_data.X.dtypes)
for element in stdized_data:
if element != 0:
log(element + 1)
else:
log(element + 2)
###################################OUTPUT################################
float64
--------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-163-6e534ce31c6a> in <module>()
9 for element in stdized_data:
10 if element != 0:
---> 11 log(str(element) + 1)
12
13 else:
TypeError: must be str, not int
I have loaded the file using pd.read_csv function.
What you need to do is probably this -
log(str(element + 1))
What you are doing is -
log(str(element) + 1)
You have converted element to string but 1 is still an integer and you can't add string and integer
I'm currently struggling with simple code, it works with seconds but I want to allow users to use minutes instead, which is much easier. Here it is:
import time
import os
import math
import subprocess
input1 = raw_input("Broj minuta:")
min = input1 * 60
min1 = float(min)
print min1
time.sleep(min1)
os.system("shutdown")
I get this error:
Broj minuta:2
Traceback (most recent call last):
File "timer.py", line 8, in <module>
time.sleep(min)
TypeError: a float is required
When I try to convert it to float using code below, it says that sleep time is big, and it is, if I choose 2 minutes I get:
min = input1 * 60
min1 = float(min)
Broj minuta:2
2.22222222222e+59
Traceback (most recent call last):
File "timer.py", line 10, in <module>
time.sleep(min1)
OverflowError: sleep length is too large
input1 = raw_input("Broj minuta:")
raw_input returns a string. You need to convert that to a number, like this
input1 = int(raw_input("Broj minuta:"))
If you don't do this, let say if you enter 2, it will still be a string and you are doing
input * 60
which means '2' * 60, which is equal to '222222222222222222222222222222222222222222222222222222222222' and it is still a string. That's why time.sleep(min) complains that
TypeError: a float is required
In the second case, you are converting '222222222222222222222222222222222222222222222222222222222222' to a float properly, but the value is 2.22222222222e+59, which is tooo big for time.sleep.
(Your traceback must be out of date; it shows time.sleep(min) (in which case the error is justified), but your code has time.sleep(min1).)
The issue is that the result of raw_input is a string. When you write input1 * 60, you repeat the string 60 times (i.e. instead of 120, you get '222222222222222222222222222222222222222222222222222222').
You're performing the conversion too late. input1 is a string, and multiplying a string by an integer
min = input1 * 60
does string repetition: '12' * 60 == '12121212...
Instead, convert to float, then multiply:
min = float(input1) * 60
The variable returned by raw_input is a string.
To add more information to what is happening in your code, here is an example session.
In [1]: i = raw_input("Something")
Something20
In [2]: i
Out[2]: '20'
In [3]: type(i)
Out[3]: str
In [4]: i*60
Out[4]: '202020202020202020202020202020202020202020202020202020202020202020202020202020202020202020202020202020202020202020202020'
In [5]: float(i*20)
Out[5]: 2.02020202020202e+39
Out [2] shows the string '20'. This is confirmed when we check the type of i, which is str.
Now, in Python, when you multiply a string with a number x, you get a string with x times the original string repeated.
This is what was happening in your code. Thus, as suggested in the other answer, you need to cast your input to a float.
Another, way of doing this (on Python 2.x) is to NOT use raw_input() and instead use input()
In [6]: j = input('Something else?')
Something else?20
In [7]: j
Out[7]: 20
In [8]: j*60
Out[8]: 1200