0

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: ""?

ur mom
  • 17
  • 5
  • If you want to replace all commas, then you can do: `'A B C 1,598 65.79 79 -300 46.90 90'.replace(',', '')` The `replace(a, b)` string method in python replaces occurences of `a` with `b` – Elijah Nicol Nov 06 '22 at 01:14
  • Does this answer your question? [replace part of the string in pandas data frame](https://stackoverflow.com/questions/42331992/replace-part-of-the-string-in-pandas-data-frame) – Henry Woody Nov 06 '22 at 01:24
  • sorry ... it doesnt do the job for me – ur mom Nov 06 '22 at 01:50

2 Answers2

1

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
Panda Kim
  • 6,246
  • 2
  • 12
  • hi, is it possible to add something to filter when is or isnt a string? (I have columns that are strings ) – ur mom Nov 06 '22 at 09:15
  • how did you write the df to show it correctly? – ur mom Nov 06 '22 at 09:15
  • `df[['A', 'B', 'C']] = df[['A', 'B', 'C']].astype('str').apply(lambda x: pd.to_numeric(x.str.replace(',', '')))` if you want apply to only 'A', 'B', 'C' columns, use indexing – Panda Kim Nov 06 '22 at 09:18
0

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).

fholl124
  • 11
  • 2