Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add string in a range creation [duplicate]

Tags:

python

I would like to create a row in order to use it as header into a dataframe.

The format is this

[a0, a1, a2]

or without comma I am not sure what it needs to paste as hearder into the dataframe.

What I tried is this:

"a" + str(range(0,3))

but the result is this:

a[0, 1, 2]
like image 700
cottinR Avatar asked Nov 27 '22 10:11

cottinR


1 Answers

Use list comprehension with format:

c = ['a{}'.format(x) for x in range(3)]
print (c)
['a0', 'a1', 'a2']

If want change columns names in pandas dataframe:

df.columns = 'a' + df.columns.astype(str)

Or use add_prefix:

df = df.add_prefix('a')

Sample:

df = pd.DataFrame([[2,3,4]])
df = df.add_prefix('a')
print (df)
   a0  a1  a2
0   2   3   4
like image 132
jezrael Avatar answered Dec 21 '22 07:12

jezrael