英文:
Python- fillna method adding .0
问题
我想在我的CSV文件中用零填充空单元格。我发现可以使用"fillna"方法来实现这一点。如果我这样做:
fillna("0")
这会在单元格为空时添加0,但如果单元格中有1,它会变成1.0,这不是我想要的。有没有办法修复这个问题?
英文:
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
得分: 1
当你使用 fillna("0") 时,它会将数值转换为字符串,这就是为什么你看到 1.0 而不是只有 1。可以用整数而不是字符串来填充它:
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)
英文:
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)
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。


评论