例如,我有一个df
<表类>
B
C
D
E
F
tbody><<tr>1 2 3 4 12 15 9 5 3 1 5 表类>
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")]))