phoenix
phoenix

Reputation: 338

Append name of dataframes to list python

I have 10 dataframes (ex: dfc,df1,df2,df3,df4,dft1,dft2,dft3,dft4,dft5). I want to check the length of each dataframe. If the length of dataframe is less than 2, I want to add the name of that dataframe to an empty list. How can I do this?

Upvotes: 0

Views: 583

Answers (2)

Samar Pratap Singh
Samar Pratap Singh

Reputation: 531

You can store the dataframes in a dictionary using their names as keys and then iterate over the dictionary:

dic = {'df1': df1,'df2': df2,'df3': df3,'df4': df4}
d = []
for k, v in dic.items():
    if len(v) < 2:
        d.append(k)
print(d)   

You can also use aa list comprehension instead of the for loop:

dic = {'df1': df1,'df2': df2,'df3': df3,'df4': df4}
d = [k for k, v in dic.items() if len(v) < 2]

Upvotes: 2

Baconflip
Baconflip

Reputation: 47

If I understand you correct, you want to create a list of the short dataframe-list. I would do it like this:

dataframes = ['d','df1','df2','df3','df4','dft1','dft2','dft3','dft4','dft5']

short_dataframe = [] # the empy list.
for frame in dataframes:
    if len(frame) < 2:
        short_dataframe.append(frame) # adds the frame to the empty list

print(short_dataframe)

result of the print = ['d']

Upvotes: 0

Related Questions