【问题标题】:Is there a way to remove empty cells(commas for empty cells) when writing to csv from pandas python?从 pandas python 写入 csv 时,有没有办法删除空单元格(空单元格的逗号)?
【发布时间】:2021-08-11 16:43:27
【问题描述】:

例如我有一个这样的df

A B C D E F
1 2 3 4
1 2
1 5 9 5 3 1
5

当我将其转换为 csv 时,我得到一个 csv,其中包含“,”用于空白单元格。浏览器

1,2,3,4,,,
1,2,,,,,
1,5,9,5,3,1
5,,,,,,

有没有办法让我只得到填充的单元格并删除带有空单元格的逗号? 预期输出为:

1,2,3,4
1,2
1,5,9,5,3,1
5

这是一个包含数百万行和数千列的大型数据集。因此试图看看我是否可以删除不必要的空格。

【问题讨论】:

  • 请以更易读的方式格式化您的预期输出。
  • @j__carlson - 为什么要在编辑中更改 OP 的示例?
  • @not_speshal 我不知道我有。

标签: python python-3.x pandas csv


【解决方案1】:
  • 定义to_csv() 以确保考虑每一列,因此将分隔空列
  • to_csv() 输出到缓冲区,然后输出strip(",") 以删除尾随逗号
  • 将此输出到文件中
import pandas as pd
import io
import numpy as np
from pathlib import Path

df = pd.DataFrame(
    {
        "A": [1, 1, 1, 5],
        "B": [2.0, 2.0, 5.0, np.nan],
        "C": [3.0, np.nan, 9.0, np.nan],
        "D": [4.0, np.nan, 5.0, np.nan],
        "E": [np.nan, np.nan, 3.0, np.nan],
        "F": [np.nan, np.nan, 1.0, np.nan],
    }
)


with open(Path.cwd().joinpath("special.csv"), "w") as f:
    f.write("\n".join([l.strip(",") for l in df.to_csv(index=False, header=None).split("\n")]))

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-09-22
    • 1970-01-01
    • 2023-01-16
    • 1970-01-01
    • 2016-01-13
    • 1970-01-01
    • 1970-01-01
    • 2021-05-05
    相关资源
    最近更新 更多