Home > Back-end >  how to replace in pandas int values with a "," for thousands with an int without ',&#
how to replace in pandas int values with a "," for thousands with an int without ',&#

Time:11-06

I have a df thats big, and has int's and float's inside, some have bigger values over 1 thousand, and that gives error when using them as int

ex:
A B C 0 1,598 65.79 79
1 -300 46.90 90

the format doesnt let me write the df

How can I replace the "," for this: ""?

CodePudding user response:

Assuming you are taking data from a CSV file, you can provide a converting function for the column. Have a look at the documentation for pd.read_csv()

For example:

import pandas as pd

def convert_value(input_value):
    return input_value.replace("Dollars", "Pounds")

df = pd.read_csv("your_file.csv", converters={"UNITS":convert_value})

^ Just something I wrote for a sample file, in your 'convert_value' function you would just do your own conversion (string to int presumably).

CodePudding user response:

df

    A       B       C
0   1,598   65.79   79
1   -300    46.90   90

use following code:

df = df.astype('str').apply(lambda x: pd.to_numeric(x.str.replace(',', '')))

check data type of result

df.dtypes

A      int64
B    float64
C      int64
dtype: object
  • Related