Skip to main content
 首页 » 编程设计

python之读取和写入 csv 文件

2024年11月01日24think

在使用 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 

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