python - Pandas 划分多个多索引列

标签 python pandas dataframe

我有一个如下所示的数据框:

dataframe

我想将 x 列除以 y 列,但目前我得到以下结果:

result dataframe

完整示例:

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

理想情况下,我想将结果作为单独的列添加回来:

enter image description here

有没有一种优雅的方式来做到这一点?

最佳答案

如果由 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 - 默认情况下会删除所选级别,因此划分效果很好(因为 xy 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

然后使用 concatDataFrame.sort_indexDataFrame.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/

相关文章:

python - 高效计算 NumPy 数组的成对相等

python - 将列表的字符串表示形式转换为带引号和双引号的列表

python - 多进程的 Spawn.Process 在 Python 中未正确填充队列

python - 如何按字符串索引上的自定义顺序对 Pandas 数据框进行排序

python - 带有 groupby 和条件的 Pandas 滚动总和

python - 在 Pandas 中读取带有 NaN 的整数时如何保留 dtype int

java - 如何从 Android 发送图像并在 GAE 上接收它?

r - 如何计算相邻行的平均值?

python - 如何在 Python pandas 中使用 pd.melt

python - 如何提取包含文本的 pandas 系列的每一行中的特定数字