Cómo agregar una fila de encabezado a un DataFrame pandas


Estoy leyendo un archivo csv en pandas. Este archivo csv consta de cuatro columnas y algunas filas, pero no tiene una fila de encabezado, que quiero agregar. He estado intentando lo siguiente:

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')

Pero cuando aplico el código, obtengo el siguiente Error:

ValueError: Shape of passed values is (1, 1), indices imply (4, 1)

¿Qué significa exactamente el error? ¿Y cuál sería una forma limpia en python de agregar una fila de encabezado a mi archivo csv/pandas df?

Author: Anton Protopopov, 2015-12-04

4 answers

Se puede utilizar names directamente en el read_csv

Nombres : similar a una matriz, por defecto Ninguno Lista de nombres de columna a usar. Archivo If no contiene ninguna fila de encabezado, entonces debe pasar explícitamente header=None

Cov = pd.read_csv("path/to/file.txt", sep='\t', 
                  names = ["Sequence", "Start", "End", "Coverage"])

La línea de abajo no funcionará como esperas. Cov ya es un dataframe, asumiendo que realmente tiene 4 columnas cuando se está leyendo desde el archivo.

Frame=pd.DataFrame([Cov], columns = ["Sequence", "Start", "End", "Coverage"])
 114
Author: Leb,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-06-08 10:08:52

Alternativamente puedes leer tu csv con header=None y luego agregarlo con df.columns:

Cov = pd.read_csv("path/to/file.txt", sep='\t', header=None)
Cov.columns = ["Sequence", "Start", "End", "Coverage"]
 58
Author: Anton Protopopov,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-03-25 21:55:48
col_Names=["Sequence", "Start", "End", "Coverage"]
my_CSV_File= pd.read_csv("yourCSVFile.csv",names=col_Names)

Habiendo hecho esto, simplemente compruébalo con [bueno, obviamente, lo sé, lo sabes. Pero aún así...

my_CSV_File.head()

Espero que ayude ... Salud

 4
Author: Bhardwaj Joshi,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-02-05 05:37:01

Para arreglar su código simplemente puede cambiar [Cov] a Cov.values, el primer parámetro de pd.DataFrame se convertirá en una matriz multidimensional numpy:

Cov = pd.read_csv("path/to/file.txt", sep='\t')
Frame=pd.DataFrame(Cov.values, columns = ["Sequence", "Start", "End", "Coverage"])
Frame.to_csv("path/to/file.txt", sep='\t')

Pero la solución más inteligente sigue siendo usar pd.read_excel con header=None y names=columns_list.

 2
Author: romulomadu,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-02-05 06:35:45