是否有一种方法来删除空单元格(逗号为空单元格)时,从pandas python写csv ?



例如,我有一个df

<表类> B C D E F tbody><<tr>1234121595315
  • 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")]))

相关内容

  • 没有找到相关文章

最新更新