Suppose we have a list of lists with 5 lists:
master_list = [list1, list2, list3, list4, list5]
I want to get the column names to be:
cols = ["list1", "list2", "list3", "list4", "list5"]
How could I extract these names from master_list
?
Edit. I guess you can manually add quotations to the elements of cols
list and then if you wanted to create a dataframe, do something like:
import pandas as pd
df_output = pd.DataFrame(list(zip(list1, list2, list3, list4, list5 )),
columns =cols)
CodePudding user response:
This is an important point. Consider the following snippet:
a = [1,2,3]
b = a
c = b
d = c
After that, how many list objects are there? The answer is 1. There is exactly one list. It happens to be bound to four different local names. (This is why doing b[1] = 9
is seen in all four names.)
The list object itself does not know any of the names to which it is bound. The list is anonymous. If you need things to be named, you use a dictionary.
master_list = {
'list1': list1,
'list2': list2,
'list3': list3,
'list4': list4
}
cols = list(master_list.keys())
CodePudding user response:
If the column names are the first values of each list then you can do this:
master_list = [
['test1', 1, 2, 3],
['test2', 1, 2, 3],
['test3', 1, 2, 3],
['test4', 1, 2, 3],
['test5', 1, 2, 3],
]
column_names = list(zip(*master_list))[0]
If you just want to create column names then this could work:
column_names = [f'list{i}' for i in range(len(master_list))]