gpt4 book ai didi

python - 在 Python 中填充 CSV 中的空点

转载 作者:行者123 更新时间:2023-12-02 04:21:32 24 4
gpt4 key购买 nike

我正在解析一个 csv 文件来创建图表。我能够毫无问题地做到这一点,除了在一个案例中......每当 csv 文件中有一个空槽时。例如:

Col1 Col2 Col3 Col4 Col5
  45   34     23     98     18
  66            25     0
  18            52     56    100

文件中第 2 列和第 5 列有两个空白条目。我想用 0 填充这些位置。我是 Python 的新手。如果 csv 中有空点,我想插入一个 0。因为我的 csv 文件中有时可能有空白,所以我得到错误 TypeError: unsupported operand type(s) for -: 'int' and 'str' .必须进入 csv 文件以检查是否有空点并手动用零填充它可能很烦人,所以我想要一种在脚本中执行此操作的方法。这是我的代码:

import pandas as pd
import matplotlib.pyplot as plt
import numpy as np


file_name = "myfile.csv"
df = pd.read_csv(file_name)
names = df['name'].values

x = np.arange(len(names))*2
w = 0.40

col2 = df.columns[1]
col3 = df.columns[2]
col4 = df.columns[3]
col5 = df.columns[4]

dif = df[col4] - df[col3]

colors = ['Red' if d < -5 else 'Blue' for d in dif]

plt.bar(x-w, df[col2].values, width=w*0.7, label=col2, color = "cyan")
plt.bar(x, df[col3].values, width=w*0.7, label=col3, color = "green")
plt.bar(x+w, df[col4].values, width=w*0.7, label=col4, color = colors)
plt.plot(x, df[col5].values, lw=2, label="Goal", color = "red")

plt.xticks(x, names, rotation='vertical')
plt.ylim([0,100])

plt.show()

注意:正如我上面提到的,我正在从 csv 文件中读取数据帧。

编辑:

我已将这一行添加到我的代码中:

df.replace(r'^\s*$', 0, regex=True)
#For testing purposes, I also added this:
print(df.replace(r'^\s*$', 0, regex=True))

我可以看到空槽现在用零填充,但我仍然收到错误 TypeError: unsupported operand type(s) for -: 'str' and 'int'对于 dif = df[col4] - df[col3] .是否可能将那些插入的 0 读取为字符串?我也试过包装 df[col3]df[col4]int()但那里没有运气。它给出错误 TypeError: cannot convert the series to <class 'int'> .然后我尝试了 df[col4].astype(int) - df[col3].astype(int)并得到错误 ValueError: invalid literal for int() with base 10 .

编辑 2:我刚刚添加了行 print(df.dtypes) .出于某种原因,第四列(在本例中包含替换的 0)被视为一个对象,而不是像其余列那样的 int64。

最佳答案

您必须使用 Pandas 库提供的 replace 方法。

这是文档:documentation .

在你的情况下你会使用

df.replace(r'^\s*$', 0, regex=True)

关于python - 在 Python 中填充 CSV 中的空点,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59495149/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com