gpt4 book ai didi

python - 使用 pandas to_csv 时删除标题中的前导逗号

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

默认情况下 to_csv 写一个 CSV 像

,a,b,c
0,0.0,0.0,0.0
1,0.0,0.0,0.0
2,0.0,0.0,0.0

但我希望它这样写:
a,b,c
0,0.0,0.0,0.0
1,0.0,0.0,0.0
2,0.0,0.0,0.0

我如何实现这一目标?我无法设置 index=False因为我想保留索引。我只想删除前导逗号。
df = pd.DataFrame(np.zeros((3,3)), columns = ['a','b','c'])
df.to_csv("test.csv") # this results in the first example above.

最佳答案

在追加模式下,可以先只写入没有索引的列,然后再写入没有标题的数据:

df = pd.DataFrame(np.zeros((3,3)), columns = ['a','b','c'], index=list('XYZ'))

pd.DataFrame(columns=df.columns).to_csv("test.csv", index=False)
#alternative for empty df
#df.iloc[:0].to_csv("test.csv", index=False)
df.to_csv("test.csv", header=None, mode='a')

df = pd.read_csv("test.csv")
print (df)
a b c
X 0.0 0.0 0.0
Y 0.0 0.0 0.0
Z 0.0 0.0 0.0

关于python - 使用 pandas to_csv 时删除标题中的前导逗号,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59897799/

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