Pandas eval with multi-index data frames

Consider the multi-index df frame:

 A bar flux B one three six three x 0.627915 0.507184 0.690787 1.166318 y 0.927342 0.788232 1.776677 -0.512259 z 1.000000 1.000000 1.000000 0.000000 

I would like to use eval to express ('bar', 'one') from ('flux', six') . Does eval syntax support this type of index?

+6
source share
1 answer

You can do this without using eval using the Python equivalent standard notation:

 df['bar']['one'] - df['flux']['six']` 

Check out this link. The following is an example for you, based on the object in your question:

 from pandas import DataFrame, MultiIndex # Create the object columns = [ ('bar', 'one'), ('bar', 'three'), ('flux', 'six'), ('flux', 'three') ] data = [ [0.627915, 0.507184, 0.690787, 1.166318], [0.927342, 0.788232, 1.776677, -0.512259], [1.000000, 1.000000, 1.000000, 0.000000] ] index = MultiIndex.from_tuples(columns, names=['A', 'B']) df = DataFrame(data, index=['x', 'y', 'z'], columns=index) # Calculate the difference sub = df['bar']['one'] - df['flux']['six'] print sub # Assign that difference to a new column in the object df['new', 'col'] = sub print df 

Corresponding result:

 A bar flux new B one three six three col x 0.627915 0.507184 0.690787 1.166318 -0.062872 y 0.927342 0.788232 1.776677 -0.512259 -0.849335 z 1.000000 1.000000 1.000000 0.000000 0.000000 
+1
source

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


All Articles