Python的fillna方法添加.0

huangapple go评论75阅读模式
英文:

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)

huangapple
  • 本文由 发表于 2023年4月10日 20:37:08
  • 转载请务必保留本文链接:https://go.coder-hub.com/75977179.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定