Jeff Saltfist Jeff Saltfist - 1 year ago 109
Python Question

Pandas - Dynamic Column Names

I have an algorithm that operates once daily. Every day the algorithm needs to create a pandas dataframe with 2 fixed column names and a column named after every value stored in a dynamic list. Having trouble figuring out how to add the column names dynamically:

# list on day 1
dynamic_list = ['variable_1','variable_2']
pd.DataFrame(results.T,columns=['fixed_1','fixed_2',(insert the 2 variable names here)])

#list on day 2
dynamic_list = ['variable_1','variable_2','variable_3']
pd.DataFrame(results.T,columns=['fixed_1','fixed_2',(insert the 3 variable names here)])

Is there a way to embed a list into the parameters that create the dataframe? All efforts thus far have failed.

Answer Source

You can try concatenating the lists like this:

pd.DataFrame(results.T,columns=['fixed_1','fixed_2'] + dynamic_list)

This works as follows:

list1 = ['a', 'b']
list2 = ['c', 'd']
list1 + list2 #['a', 'b', 'c', 'd']
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download