gpt4 book ai didi

python - 读取和写入 csv 文件

转载 作者:太空宇宙 更新时间:2023-11-04 04:05:11 24 4
gpt4 key购买 nike

在使用 pandas 库时,我想读取数据并将数据写入 csv 文件。使用 to_csv 将 DataFrame 写入 csv 文件一切正常。当我尝试将值读回 python 解释器时,我的问题出现了。

参数 index_col=None 不会改变输出。

#Pass some keys and values to a pandas DataFrame held in variable df
df = pd.DataFrame({'Artist':['Sublime','Blink 182','Nirvana'],
'Album':['Sublime','Blink 182','Nevermind'],
'Hit Single':["What I've Got", 'All the Small Things',
'Smells Like Teen Spirit']})

#Print DataFrame
df


#Write the data to a spreadsheet(comma separated value file type)
df.to_csv('filename.csv')

#Read the values back into the df varaible
df =pd.read_csv('filename.csv')

#Print out values in df variable
df

使用 read_csv 读回数据后,第二列顶部有未命名:以及一组额外的数字索引,从 0 到 2 0 出现两次。我怎样才能去掉这个多余的不需要的列?

最佳答案

发生这种情况是因为您正在将 index 保存到文件中。您可以使用:

df.to_csv('filename.csv', index=False)

df =pd.read_csv('filename.csv')
df
Out[1]:
Artist Album Hit Single
0 Sublime Sublime What I've Got
1 Blink 182 Blink 182 All the Small Things
2 Nirvana Nevermind Smells Like Teen Spirit

这应该可以防止创建额外的列,因为它不会将索引保存到新文件中。

关于python - 读取和写入 csv 文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57485200/

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