Home > OS >  How to create a sequenced header in pandas in a dataframe?
How to create a sequenced header in pandas in a dataframe?

Time:12-09

I am currently working with a large CSV file that contains about 1000 rows × 129 columns. However, it does not include a header.

I would like to add a header on the top row that says value1, value2, .... value129 for each column respectively.

I am currently testing using this code:


import pandas as pd

df = pd.read_csv('file.csv', sep='\t', names=[???])


My issue is in this section ??? I think. I know that i could replace wit with 'value1','value2',....'value129' but that would take a lot of space.

Can anyone suggiest me a better and faster method? where I could fill out the new header row automaticly?

I appriciate it thanks!

CodePudding user response:

First set header=None for default range columns names like 0,1,...

If possible start columns from 0 like value0, values1, ... use DataFrame.add_prefix:

df = pd.read_csv('file.csv', sep='\t', header=None).add_prefix('value')

If need start by 1 like value1, values2, ...:

f = lambda x: f'value{x   1}'
df = pd.read_csv('file.csv', sep='\t', header=None).rename(columns=f)

Or set in list comprehention by columns names:

df = pd.read_csv('file.csv', sep='\t', header=None)
df.columns = [f'value{x   1}' for x in df.columns]

CodePudding user response:

Simple solution. try this:

df.columns = ['value{}'.format(num 1) for num in range(129)]

Sample output:

['value1', 'value2', 'value3', 'value4', 'value5', 'value6', 'value7', 'value8', 'value9', 'value10', 'value11', 'value12', 'value13', 'value14', 'value15', 'value16', 'value17', 'value18', 'value19', 'value20', 'value21', 'value22', 'value23', 'value24', 'value25', 'value26', 'value27', 'value28', 'value29', 'value30', 'value31', 'value32', 'value33', 'value34', 'value35', 'value36', 'value37', 'value38', 'value39', 'value40', 'value41', 'value42', 'value43', 'value44', 'value45', 'value46', 'value47', 'value48', 'value49', 'value50', 'value51', 'value52', 'value53', 'value54', 'value55', 'value56', 'value57', 'value58', 'value59', 'value60', 'value61', 'value62', 'value63', 'value64', 'value65', 'value66', 'value67', 'value68', 'value69', 'value70', 'value71', 'value72', 'value73', 'value74', 'value75', 'value76', 'value77', 'value78', 'value79', 'value80', 'value81', 'value82', 'value83', 'value84', 'value85', 'value86', 'value87', 'value88', 'value89', 'value90', 'value91', 'value92', 'value93', 'value94', 'value95', 'value96', 'value97', 'value98', 'value99', 'value100', 'value101', 'value102', 'value103', 'value104', 'value105', 'value106', 'value107', 'value108', 'value109', 'value110', 'value111', 'value112', 'value113', 'value114', 'value115', 'value116', 'value117', 'value118', 'value119', 'value120', 'value121', 'value122', 'value123', 'value124', 'value125', 'value126', 'value127', 'value128', 'value129']

  • Related