Add row in range creation

I would like to create a row to use it as a title in a dataframe.

Format is

[a0, a1, a2]

or without a comma I'm not sure what it needs to be inserted as a listener in the dataframe.

I tried this:

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

but the result is this:

a[0, 1, 2]
+4
source share
8 answers

Use list with format:

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

If you want to change the column names in the pandas dataframe:

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

Or use add_prefix:

df = df.add_prefix('a')

Example:

df = pd.DataFrame([[2,3,4]])
df = df.add_prefix('a')
print (df)
   a0  a1  a2
0   2   3   4
+7
source
range(0, 3)

returns a list like this:

[0, 1, 2]

If you want this to become [a0, a1, a2], you could use list comprehension.

eg.

myList = ["a" + str(val) for val in range(0, 3)]

If you have not used lists, then this is just a concise way of writing

myList = []
for val in range(0, 3):
    myList.append("a" + str(val))

After that myList will be

['a0', 'a1', 'a2']
+5
source

map:

new_data = map(lambda x:"a{}".format(x), range(3))

:

['a0', 'a1', 'a2']

:

new_string = ("a{} "*3).format(*range(3)).split()

:

['a0', 'a1', 'a2']
+5

'a' . :

column_names = range(3)
column_names = ['a'+str(i) for i in x]

columns .

+3

, f-strings ( Python 3.6 +):

[f'a{i}' for i in range(3)]
+3

header = ["a" + str(x) for x in range(0,3)]

["a0","a1","a2"]
+2

:

["a" + str(i) for i in range(0,3)]
+2

, , :

b = []
for i in range(0, 3):  
    c = "a" + str(i)
    b.append(c)

range() append(), .

+2

Source: https://habr.com/ru/post/1691591/


All Articles