How to remove extra column headings from a .csv file

时间:2017-03-22 18:45:17

标签: python csv pandas

I have written data to a .csv file but it gives me extra values for the column indexes and I cant remove them.

values1 = featureVectors
header1 = ["Dataset Number","Number of Sides", "Standard Deviation of Number of Sides/Perimeter",
      "Standard Deviation of the Angles", "Largest Angle"]
my_df = pd.DataFrame(featureVectors)
my_df.to_csv('featureVectors.csv', index=True, header=True, index_label=header1)

I have just used a few values as an example.

What my .csv looks like

I need to get rid of the extra column headings(0,1,2,3) but cant figure it out.

Thanks.

4 个答案:

答案 0 :(得分:1)

试试这个:

my_df.iloc[:, :len(header1[1:])] \
     .to_csv('featureVectors.csv', index=True, header=header1[1:], index_label=header1[0])

答案 1 :(得分:0)

my_df.to_csv('featureVectors.csv', index=True, header=header1)

答案 2 :(得分:0)

根据pandas.DataFrame.to_csv documentation,参数标头收到一个字符串列表或一个布尔值(默认为True)。

如果您将标题列表传递给header参数并删除index_label参数,它将根据您的意愿打印列名称。

我希望这会有所帮助。

答案 3 :(得分:0)

感谢您提出的建议和意见。我必须在答案之上再做一步。我更正的代码是:

values1 = featureVectors
header1 = ["Number of Sides", "Standard Deviation of Number of Sides/Perimeter",
      "Standard Deviation of the Angles", "Largest Angle"]
my_df = pd.DataFrame(featureVectors)
my_df.to_csv('featureVectors.csv', index=True, header=header1)

然后我删除了

index_label=header1 

并改变了

header=True

`header=header1`

如果我只是做了这两件事我会得到错误

ValueError: Writing 4 cols but got 5 aliases

所以我不得不删除第一个列标题“Dataset Number”来纠正这个问题。

This is the resulting .csv file