Home > Mobile >  problem when I create a function and it does not transform to float
problem when I create a function and it does not transform to float

Time:11-19

I am trying to create a function miles to KM, but the result is float and does not transform it. Distance: is a column in integer format.

the function 'miles_a_KM' receives the parameter miles, which is an integer column.

def miles_to_KM(miles):
    MIc = 1.609344
    km = miles * MIc
    return(pd.DataFrame({'km':km}).fillna(0))

the problem.

---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
Input In [8], in <cell line: 1>()
----> 1 miles_to_KM('Distance')

Input In [7], in miles_to_KM(miles)
      1 def miles_to_KM(miles):
      2     MIc = 1.609344
----> 3     km = miles * MIc
      4     return(pd.DataFrame({'km':km}).fillna(0))

TypeError: can't multiply sequence by non-int of type 'float'

try

return(pd.DataFrame({'km':km}).astype(float).fillna(0))

CodePudding user response:

Looks like when you call the function your input parameter is a string. Not sure if you only want to convert 1 value in the column to miles, however, to access the value from the dataframe you may want to try miles_to_KM(dataframename.iloc[0]["Distance"]

The error come from trying to multiply a string value by a float, this could be possible using an integer such as

def mile_to_KM(miles):
     MIc = 2
     return MIc * miles

and so mile_to_KM("Distance") would output Distance Distance. Hope this makes the error message makes a bit more sense now as using a float to multiply a string would not compute.

CodePudding user response:

Why not simply using pandas.Series.div ?

#dataset: http://ksgleditsch.com/data/capdist.csv

MIc = 1.60934

df["milesdist"]= df["kmdist"].div(MIc).round(2)

# Output :

print(df)

   ida  idb  kmdist  milesdist
0  UKR  TUR    1231     764.91
1  FIN  NIC    9962    6190.12
2  SUR  BUI    9430    5859.54
3  CAN  ZAN   12416    7714.96
4  SYR  MSI   13081    8128.18
5  BEL  CHN    8080    5020.69
6  NEP  NTH    7034    4370.74
7  GRG  GFR    3119    1938.06
8  TKM  THI    4953    3077.66
9  AZE  BOS    2611    1622.40
  • Related