Home > database >  How to delete coma of numbers contained in the dataframe's column?
How to delete coma of numbers contained in the dataframe's column?

Time:01-04

Values of column "Daily Oil Consumption (Barrels)" contain comas . i would delete this because this variable considered as object not a intiger.

CodePudding user response:

To remove the commas just use the str.replace() function.

>>> my_text = "Hi, my name is Kaleb"
>>> my_text = my_text.replace(",","")
>>>
>>>
>>> print(my_text)
Hi my name is Kaleb

Inside the parenthesis the first parameter is the old text, the second parameter is the text you want to replace it with.

In this case you want to replace a "," with nothing, so just "".

Here's an example:

df['Daily Oil Consumption (Barrels)'] = df['Daily Oil Consumption (Barrels)'].str.replace(',', '')

CodePudding user response:

Just expanding the @KalebFenley answer, you need to do the replacement to remove the commas

df['Daily Oil Consumption (Barrels)'] = df['Daily Oil Consumption (Barrels)'].str.replace(',', '')

And also, as @Yousef mentioned, you need to cast it as int, the full line of code should be something like this.

df['Daily Oil Consumption (Barrels)'] = df['Daily Oil Consumption (Barrels)'].str.replace(',', '').astype(int)

And that should work for this specific case, however, my personal recommendation is that you should use the pandas function "to_numeric", because in that way you can avoid exceptions if your data includes some "non-numeric" values.

df['Daily Oil Consumption (Barrels)'] = pd.to_numeric(df['Daily Oil Consumption (Barrels)'], errors='coerce')

If you don't have that issue, just proceed with the previous suggestion.

CodePudding user response:

I think this answer can help you.

So, you can do this:

df1['Daily Oil Consumption (Barrels)'] = df1['Daily Oil Consumption (Barrels)'].str.replace(',', '')
df1['Daily Oil Consumption (Barrels)'] = df1['Daily Oil Consumption (Barrels)'].astype(int)
  • Related