0

I am facing an issue in data frame of removing .0

My data looks like

Age
3.5
9.0
7.6
8.7
4.0

And I want it to looks like

 Age
 3.5
 9
 7.6
 8.7
 4

It's only a sample, the real data frame is too big with more than 50 columns having the same problem, so please suggest me the answer which can directly be applied to the whole data frame instead of individual columns.

I am trying to convert by below method but it's not working

def myconverter(o):
if isinstance(o, float):
    if o == int(o):
        return int(o)
return o.__str__()



org.postgresql.util.PSQLException: ERROR: invalid input syntax for integer: "309.0"
Anil
  • 133
  • 1
  • 8

1 Answers1

0

You could probably apply if condition

def transform_value(val):
    if val % 1 == 0: #val is the value for which you are checking
        return (int(val))
    else:
        return val

df['value'] = df['value'].apply(transform_value) #for single columns
df = df.apply(transform_value) # for entire dataframe

Hopefully, this answers it. I am interested in knowing the use case of why you need that.

aayush_malik
  • 161
  • 13
  • I am transferring data from one database to another based on the date, So in this case, I am having a huge data frame. And my error is org.postgresql.util.PSQLException: ERROR: invalid input syntax for integer: "309.0" Your suggestion is good but it's not solving my problem def myconverter(o): if isinstance(o, float): if o == int(o): return int(o) return o.__str__() – Anil Jan 08 '20 at 13:50
  • I have edited the code. please try now, once transformed, the database can be exported. do you think it might help? – aayush_malik Jan 08 '20 at 13:58
  • After applying the method I am getting this error on df.columns = map(str.upper, df.columns) AttributeError: 'Series' object has no attribute 'columns' – Anil Jan 09 '20 at 07:37
  • if you want to apply to the entire dataframe then use `df = df.apply(transform_value)` and if you want just for one column please use the name of that column. In your case, I guess you want to apply to the entire frame. the last two lines of my answer may answer your this comment – aayush_malik Jan 10 '20 at 07:46