如何添加标题行到pandas DataFrame [英] How to add header row to a pandas DataFrame
问题描述
我正在读一个csv文件到 pandas
。这个csv文件包含四列和一些行,但没有标题行,我想添加。我一直在尝试以下:
Cov = pd.read_csv(path / to / file.txt,sep = \t')
Frame = pd.DataFrame([Cov],columns = [Sequence,Start,End,Coverage])
Frame.to_csv(path / to / file.txt,sep ='\t')
,我得到以下错误:
ValueError:传递值的形状是(1,1),索引隐含)
错误是什么意思?在python中添加标题行到csv文件/ pandas df?
names
直接在 read_csv
names:array-like,使用。如果文件
不包含标题行,则应显式传递header = None
Cov = pd.read_csv(path / to / file.txt,sep ='\t',
names = [Sequence,Start,End,Coverage])
下面的行不能正常工作。 Cov
已经是一个数据框架,假设它从文件中读取时确实有4列。
Frame = pd.DataFrame([Cov],columns = [Sequence,Start,End,Coverage])
pre>
I am reading a csv file into
pandas
. This csv file constists of four columns and some rows, but does not have a header row, which I want to add. I have been trying the following:Cov = pd.read_csv("path/to/file.txt", sep='\t') Frame=pd.DataFrame([Cov], columns = ["Sequence", "Start", "End", "Coverage"]) Frame.to_csv("path/to/file.txt", sep='\t')
But when I apply the code, I get the following Error:
ValueError: Shape of passed values is (1, 1), indices imply (4, 1)
What exactly does the error mean? And what would be a clean way in python to add a header row to my csv file/pandas df?
解决方案You can use
names
directly in theread_csv
names : array-like, default None List of column names to use. If file contains no header row, then you should explicitly pass header=None
Cov = pd.read_csv("path/to/file.txt", sep='\t', names = ["Sequence", "Start", "End", "Coverage"])
The line below will not work as you expect.
Cov
is already a dataframe, assuming it really has 4 columns when it's being read from the file.Frame=pd.DataFrame([Cov], columns = ["Sequence", "Start", "End", "Coverage"])
这篇关于如何添加标题行到pandas DataFrame的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!