考虑多索引数据框df
:
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
我想使用eval
从('bar', 'one')
中减去('flux', six')
。 eval语法是否支持这种类型的索引?
答案 0 :(得分:1)
您可以在不使用eval
的情况下使用等效的标准Python表示法来执行此操作:
df['bar']['one'] - df['flux']['six']`
查看this参考。以下是您的示例,基于您问题中的对象:
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
相应的结果是:
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