dataframe合并并生成3d数据框架



我有四个dfs

dfB = pd.DataFrame([[cheapest_brandB[0],wertBereichB]], columns=['brand', 'price'], index= 
['cheap'])
dfC = pd.DataFrame([[cheapest_brandC[0],wertBereichC]], columns=['brand', 'price'], index= 
['cheap'])
dfG = pd.DataFrame([[cheapest_brandG[0],wertBereichG]], columns=['brand', 'price'], index= 
['cheap'])
dfO = pd.DataFrame([[cheapest_brandO[0],wertBereichO]], columns=['brand', 'price'], index= 
['cheap'])

结果:


brand                             price
cheap  ASUS                {'gte': 821.84, 'lte': 1200.91}
brand                            price
cheap    HP                {'gte': 187.82, 'lte': 993.73}
brand                            price
cheap  Google              {'gte': 1047.3, 'lte': 2093.59}
brand                            price
cheap   MSI                {'gte': 1047.3, 'lte': 2093.59}

,我想让3d df,这样它们每个都属于一个特定的索引像这样的

Gaming                                         Casual                      ....
brand             price                     brand           price
cheap   ASUS    {'gte': 821.84, 'lte': 1200.91}     HP      {'gte': 187.82, 'lte': 993.73}    ....
light   ..                 ..                       ..                 ..

使用您提供的数据帧:

import pandas as pd
dfs = [
pd.DataFrame(
{"brand": ["ASUS"], "price": [{"gte": 821.84, "lte": 1200.91}]}, index=["cheap"]
),
pd.DataFrame(
{"brand": ["HP"], "price": [{"gte": 187.82, "lte": 993.73}]}, index=["cheap"]
),
pd.DataFrame(
{"brand": ["Google"], "price": [{"gte": 1047.3, "lte": 2093.59}]},
index=["cheap"],
),
pd.DataFrame(
{"brand": ["MSI"], "price": [{"gte": 1047.3, "lte": 2093.59}]}, index=["cheap"]
),
]

有一种方法:

for df, name in zip(dfs, ["Gaming", "Casual", "Pro", "Other"]):
df.columns = pd.MultiIndex.from_product([[name], ["brand", "price"]])
df = pd.concat(dfs, axis=1)

所以:

print(df)
# Output
Gaming                                  Casual  
brand                            price  brand   
cheap   ASUS  {'gte': 821.84, 'lte': 1200.91}     HP   
Pro  
price   brand   
cheap  {'gte': 187.82, 'lte': 993.73}  Google   
Other
price brand                            price  
cheap  {'gte': 1047.3, 'lte': 2093.59}   MSI  {'gte': 1047.3, 'lte': 2093.59}  

最新更新