Można to zrobić bez użycia eval
za pomocą notacji standardowy odpowiednik Python:
df['bar']['one'] - df['flux']['six']`
Spójrz na this odniesienia. Poniżej znajduje się przykład dla ciebie, opiera się obiekt w swoim pytaniu:
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
Odpowiedni wynik jest:
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
myślę, że jest wsparcie dla indeksu MI ale nie kolumny MI, zobacz https://github.com/pydata/pandas/pull/4164#issuecomment-24009601. Obejście/włamanie polega na ustawieniu kolumn, wykonaniu zapytania, zresetowaniu kolumn (ponieważ jest to zazwyczaj tania operacja). –