1

I want to fill empty cells in my csv file with zeros. I found that I can do this with fillna metod. It I do this:

fillna(“0”) 

This will add 0 if cell is empty but if the cell has for example 1 it is changed to 1.0 which I don’t want. Is there any way to fix it?

1 Answer 1

1

When you use fillna("0"), it converts the numeric values to strings, and that's why you see 1.0 instead of just 1. Just fill it with integer instead of strings like that:

import pandas as pd

df = pd.read_csv("your_csv_file.csv")

df.fillna(0, inplace=True)

float_cols = df.select_dtypes(include=['float64']).columns
convertible_cols = [col for col in float_cols if (df[col] % 1 == 0).all()]

df[convertible_cols] = df[convertible_cols].astype(int)

df.to_csv("updated_csv_file.csv", index=False)
Sign up to request clarification or add additional context in comments.

2 Comments

This gives me 0.0 and not 0 and also changed the 1 to 1.0
I updated my code, I think pandas is messing arround with csv files

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.