Reputation: 77
I am trying to find the minimum value of the column's data without using inbuilt function.
Can anyone please help me on this below issue.
import pandas as pd
file_loc= 'filepath'
data= pd.read_csv(file_loc)
cpiData= data['cpi'].unique()
minValue =data['cpi'].head(0)
print("type of min ", type(minValue))
min=100
for i in cpiData:
print(type(i),"min", minValue.astype(float))
**if minValue.astype(float) > float(i): # getting the error while comparing both the values.**
minValue=i
print(min,"Minimum value ")
Upvotes: 0
Views: 436
Reputation: 31011
The first correction pertains to the way how to select
the initial value of minValue.
Note that your formula (data['cpi'].head(0)
) actually means:
data['cpi']
- take cpi column,head(0)
- get 0 initial elements,so the result is an empty Series.
The correct formula is: minValue = data.iloc[0].cpi
, i.e.:
data.iloc[0]
- take the initial row from data (it is a Series),cpi
- read cpi from it.The rest of your program (a loop, with diagnostic printouts) can be changed to:
for i in cpiData:
print(i)
if minValue > i:
minValue = i
print('New min')
Note that your column is already of float type, so you don't need to convert it to float.
And to print the result after the loop, print minValue, not min (min is a built-in function):
print('Minimum value:', minValue)
Actually, your instruction min=100
overwrites built-in function min
with an integer value. Don't do such things, as it destroys your working
environment.
Upvotes: 0
Reputation: 3591
Pandas head()
returns the first n rows of your column data['cpi']
. The type of return value is pandas.core.series.Series
.
First of all, you may have a bug by returning head(0)
. It simply returns an empty series.
The astype()
function changes the type of all elements in the given object to the given dtype
. Here, the input object is a Series
(resulting from your call to head(0)
), so the output object will also be a Series
, which would contain float
values.
Now, you are comparing a Series
(the minValue.astype(float)
) with a float
(the float(i)
), and the error is saying "I don't know how to compare this Series
object to a float
", which makes sense.
You can do:
minValue[0].astype(float) > float(i)
to compare the frist element of Series to i
. However be ware of the above mentioned potential bug: your series actually does not contain anything, because you are calling head(0)
instead of head(1)
.
Upvotes: 0