Using DataFrame.ix with tuple index in Pandas

I have a bunch of Pandas code that uses tuples as indexes. I recently encountered the need to access a single DataFrame element using a DataFrame.ix , which confuses tuples. It seems that my tuple is the sequence of keys that I want to access, and not the individual keys (which happen to be the sequence) that I want to access. How can I extract a single row for which the key is the key?

Perhaps this is a warning story not to use sequences in the Pandas index, but in my case it is too late.

 import string, pandas as pd, numpy as np bar = pd.DataFrame(np.random.random((8,2))) bar.columns = ['col1', 'col2'] bar.index = list(string.ascii_lowercase)[:8] print bar print bar.iloc[0].name print bar.ix[bar.iloc[0].name] bar.index = [tuple(list(string.ascii_lowercase)[i:i+3]) for i in range(8)] print bar.iloc[0].name print bar.ix[bar.iloc[0].name] # Fails with `KeyError: 'a'` 
+3
source share
2 answers

You can wrap a tuple in a list to do this job.

 In [17]: bar.ix[[bar.iloc[0].name]] Out[17]: col1 col2 (a, b, c) 0.216689 0.262511 
+6
source

I don't think this can be done with indexing, but you can do it with xs :

 >>> bar.xs(bar.iloc[0].name) col1 0.864788 col2 0.708136 Name: (a, b, c), dtype: float64 
+3
source

Source: https://habr.com/ru/post/1011572/


All Articles