Python 合并多索引数据帧内的列
我有一个多索引数据帧,看起来像这样(很抱歉,我无法通过代码复制数据帧): 产品是一样的,但顺序不同。价格需要分开 我希望有一个单独的产品栏,其他栏是价格栏,如下所示:Python 合并多索引数据帧内的列,python,pandas,Python,Pandas,我有一个多索引数据帧,看起来像这样(很抱歉,我无法通过代码复制数据帧): 产品是一样的,但顺序不同。价格需要分开 我希望有一个单独的产品栏,其他栏是价格栏,如下所示: 这是创建多索引数据帧的一种方法 tuples = list(zip(*[ ["a","a","b","b","c","c"], ["product","price&
这是创建多索引数据帧的一种方法
tuples = list(zip(*[
["a","a","b","b","c","c"],
["product","price","product","price","product","price"],
]))
columns = pd.MultiIndex.from_tuples(tuples)
df = pd.DataFrame(
[['apple', 1, 'oranges', 2, 'bananas', 1],
['oranges', 4, 'bananas', 3, 'oranges', 2],
['bananas', 5, 'apple', 4, 'apple', 3]],
columns=columns)
df
输入
a b c
product price product price product price
0 apple 1 oranges 2 bananas 1
1 oranges 4 bananas 3 oranges 2
2 bananas 5 apple 4 apple 3
a b c
0 apple 1 4 3
1 bananas 5 3 1
2 oranges 4 2 2
代码
df = df.stack(0).reset_index(1).pivot(
columns='level_1', index='product').reset_index()
df.columns = df.columns.droplevel(0).rename(None)
df
输出
a b c
product price product price product price
0 apple 1 oranges 2 bananas 1
1 oranges 4 bananas 3 oranges 2
2 bananas 5 apple 4 apple 3
a b c
0 apple 1 4 3
1 bananas 5 3 1
2 oranges 4 2 2
“很抱歉,我无法通过代码复制数据帧”为什么不能?