我有一个如下所示的数据框:
我想将 x
列除以 y
列,但目前我得到以下结果:
完整示例:
import pandas as pd
# create example dataframe
data = {'x': [2, 4, 6], 'y': [1, 2, 3]}
df = pd.DataFrame(data)
df = pd.concat([df, df*10], axis=1, keys=['apple', 'orange'])
# slice just x and y columns
x = df.loc[:, (slice(None), 'x')]
y = df.loc[:, (slice(None), 'y')]
# divide (this doesn't work)
result = x / y
理想情况下,我想将结果作为单独的列添加回来:
有没有一种优雅的方式来做到这一点?
最佳答案
如果由 rename
创建相同的第二级,则您的解决方案可以正常工作:
new = (x.rename(columns={'x':'x/y'}) / y.rename(columns={'y':'x/y'})
print (new)
apple orange
x/y x/y
0 2.0 2.0
1 2.0 2.0
2 2.0 2.0
或者可以使用DataFrame.xs
- 默认情况下会删除所选级别,因此划分效果很好(因为 x
和 y
DataFrame
中的列相同),因此有必要创建第二个级别通过 MultiIndex.from_product
:
x = df.xs('x', axis=1, level=1)
y = df.xs('y', axis=1, level=1)
new = x / y
new.columns = pd.MultiIndex.from_product([new.columns, ['x/y']])
print (new)
apple orange
x/y x/y
0 2.0 2.0
1 2.0 2.0
2 2.0 2.0
然后使用 concat
与 DataFrame.sort_index
和 DataFrame.reindex
:
df = pd.concat([df, new], axis=1).sort_index(axis=1).reindex(['x','x/y','y'], axis=1, level=1)
print (df)
apple orange
x x/y y x x/y y
0 2 2.0 1 20 2.0 10
1 4 2.0 2 40 2.0 20
2 6 2.0 3 60 2.0 30
关于python - Pandas 划分多个多索引列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57212931/