首页 > 解决方案 > 读取和写入 csv 文件

问题描述

在使用 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 读回数据后,在第二列的顶部有 Unnamed: 以及从 0 计数到 2 0 的一组额外的数字索引出现两次。我怎样才能摆脱这个多余的不需要的列?

标签: pythonpandas

解决方案


发生这种情况是因为您将 保存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

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


推荐阅读