Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create a list of strings with consecutive numbers appended

Tags:

python

pandas

I'm sure there must e an easy way to do this: I want to create a list which will eventually become column names for a DataFrame. There will be 13 columns, each representing a period in time, called "Period n", where n is the period number. I think there's probably a way to build this list via loop, but I will show what I tried to do:

col_no = list(range(1,14))
col_name = ['Period' for n in range (1,14)]
col_list = col_name + col_no

print(col_list)

['Period',
 'Period',
 'Period',
 'Period',
 'Period',
 'Period',
 'Period',
 'Period',
 'Period',
 'Period',
 'Period',
 'Period',
 'Period',
 1,
 2,
 3,
 4,
 5,
 6,
 7,
 8,
 9,
 10,
 11,
 12,
 13]

Then I tried:

col_list = list(zip(col_name + col_no))
print(col_list)

[('Period',),
 ('Period',),
 ('Period',),
 ('Period',),
 ('Period',),
 ('Period',),
 ('Period',),
 ('Period',),
 ('Period',),
 ('Period',),
 ('Period',),
 ('Period',),
 ('Period',),
 (1,),
 (2,),
 (3,),
 (4,),
 (5,),
 (6,),
 (7,),
 (8,),
 (9,),
 (10,),
 (11,),
 (12,),
 (13,)]

Basically, I just wanted an easily generated list that reads "Period 1", "Period 2", etc. I'm pretty new to Python, and pretty stumped.Thanks in advance

like image 316
jules325 Avatar asked Jul 10 '18 17:07

jules325


1 Answers

You can concatenate them (the number and the word Period) together while the loop iterates.

Python 3.6+

print([f'Period {i}' for i in range(1, 14)])

Python 2.7+

print(['Period {}'.format(i) for i in range(1, 14)])
like image 188
Neil Avatar answered Oct 01 '22 01:10

Neil