Iterating over a list made up of distinct dataframes

Viewed 40

Suppose I have a list that is made up of 3 dataframes, namely

lst = [df1,df2,df3]

where:

d1 = {'col1':['a','b','c','d','e']}
df1= pd.DataFrame(d1)
d2 = {'col1':['b','c','a','d','e']}
df2= pd.DataFrame(d2)
d3 = {'col1':['b','c','e','d','a']}
df3= pd.DataFrame(d3)

for each df in the lst I want to go through col1 and find the rank of letter a and make a new dataframe from it, the output should look like:

  dataframe index  rank of a
0                0          0
1                1          2
2                2          4

namely, for df1 letter a is on 0th index, for df2 letter a is on 2nd index and so on. I wonder how one does this?

I tried doing:

ll = []
for i in lst:
    x = i[i['col1'].isin(['a'])]
    ll.append(x)

which extracts the ranks of a, I then tried

lll = []
for i in ll:
    x = ll[i][0]
    lll.append(x)

which doesn't work and I think my approach generally is not the best way.

2 Answers

You can just have a simple loop to go through your dfs:

rank_a = []
for df in lst:
    rank_a.append(df[df.col1 == "a"].index[0])

# rank_a = [0,2,4]

The idea is to filter for rows with "a" in col1 and use the index for rank. The code above assumes "a" will always be col1, so taking the first one. As long as the dfs are having default index, it will be fine, if not you can always reset the index.

Then construct your final df:

rank_df = pd.DataFrame({
    "dataframe index": range(len(lst)),
    "rank of a": rank_a
})

Try:

pd.DataFrame({
    'df': range(len(lst)),
    'rank_of_a': [df['col1'].eq('a').idxmax() for df in lst]
})

Output:

   df  rank_of_a
0   0          0
1   1          2
2   2          4
Related