Can't Get Index Position From List Of Dataframes
Solution 1:
As others have said, you can use enumerate to do what you want.
As to why what you're trying isn't working:
list.index(item) looks for the first element of the list such that element == item. As an example consider df = dfs[0]. When we call dfs.index(df), we first check whether df == the first element of dfs. In other words we are checking whether df == df. If you type this into your interpreter you will find that this gives you a DataFrame of Trues. This is a DataFrame object -- but what Python wants to know is whether it should consider this object as True or not. So it needs to convert this DataFrame into a single bool. It tries to do this via bool(df == df), which relies on pandas implementing a method that converts any DataFrame into a bool. However there is no such method, and for good reason -- because the correct way to do this is ambiguous. So at this point pandas raises the error that you see.
In summary: for index to make sense, the objects must have some notion of equality (==), but DataFrames don't have such a notion, for good reason.
If in a future problem you need to find the index of a DataFrame within a list of DataFrames, you first have to decide on a notion of equality. One sensible such notion is if all the values are the same. Then you can define a function like:
defindex(search_dfs, target_df):
for i, search_df inenumerate(search_dfs):
if (search_df.values == target_df.values).all():
return i
return ValueError('DataFrame not in list')
index(dfs, df[2])
Out: 2Solution 2:
Use enumerate :
for i, dfin enumerate(dfs):
print(i)
Solution 3:
I guess you want to do something like this:
dfs = [df1, df2, df3]
for i, dfin enumerate(dfs):
print(i)
And this is not a pandas related question. It's simply Python question.
Post a Comment for "Can't Get Index Position From List Of Dataframes"