简体   繁体   中英

Fast way to fill a python list to target length

I want to fill one of my list to the same length with the others, so they can be used in later pandas

df = pd.DataFrame([list1,list2,list3],columns= column_name_list)

for example, my column_name_list is with length 5 but if list1,list2,list3 is only with length 3, eg:

list1= ['a','b','c']

Before parsing it to dataframe, is there any fast way(like single line) to fill the list1 to target length 5? What I expect is list1 to be

['a','b','c','empty_or_the_string_I_defined_or_from_target_list','empty_or_the_string_I_defined_or_from_target_list']

I want to fill the rest with blank or specific string or even the same element as target column name list

Thanks!

One way using itertools.zip_longest :

from itertools import zip_longest

list1 = ["a", "b", "c"]
list2 = ["aa", "bb"]
list3 = ["aaa", "bbb", "ccc", "ddd"]
columns = ['col0', 'col1', 'col2', 'col3', 'col4']

padded = list(zip_longest(columns, list1, list2, list3, fillvalue="Fillme"))
print(padded)

Output:

[('col0', 'a', 'aa', 'aaa'),
 ('col1', 'b', 'bb', 'bbb'),
 ('col2', 'c', 'Fillme', 'ccc'),
 ('col3', 'Fillme', 'Fillme', 'ddd'),
 ('col4', 'Fillme', 'Fillme', 'Fillme')]

You can then use pandas.DataFrame.set_index with T to make a dataframe:

df = pd.DataFrame(padded).set_index(0).T
print(df)

Output:

0 col0 col1    col2    col3    col4
1    a    b       c  Fillme  Fillme
2   aa   bb  Fillme  Fillme  Fillme
3  aaa  bbb     ccc     ddd  Fillme

The easiest might be:

  list1 + ['empty_or_the_string_I_defined_or_from_target_list'] * (target_length - len(list1))

This should do the trick.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM