Values of column "Daily Oil Consumption (Barrels)" contain comas . i would delete this because this variable considered as object not a intiger.
-
1Does this help: [search-and-replace-dots-and-commas-in-pandas-dataframe](https://stackoverflow.com/questions/49088443/search-and-replace-dots-and-commas-in-pandas-dataframe). Also here: [convert-number-strings-with-commas-in-pandas-dataframe-to-float](https://stackoverflow.com/questions/22137723/convert-number-strings-with-commas-in-pandas-dataframe-to-float) – topsail Jan 03 '23 at 15:54
-
i want to delete the comas contained in the third column "Daily Oil Consumption (Barrels) " because this variable is considered as object but not as integer. – emmanuel Jan 03 '23 at 15:56
3 Answers
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(',', '')

- 216
- 1
- 5
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.

- 46
- 7
-
1
-
Just in case, I've already added another option that would work if you have data that is not a number, however, if you strictly want to have integers the existing suggestions should be enough and would notify you when you have dirty data. @emmanuel – Erick IO Jan 03 '23 at 18:58
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)

- 11
- 1
- 5