首页 > 解决方案 > 将行与不同格式的熊猫列合并

问题描述

我有一个数据框,其中有 n 个相同标题的列,例如。销售、销售 1、销售 2 等

并且数据是多条记录的行,其中一列具有 ID 并且 ID 列具有重复值。

销售列有第一行说明月份,例如销售销售 1 的一月、二月等

Sales      Sales1     Sales2
Jan 2000  Feb 2000   Month 2000
2000       3000       4000

我已将 Sales 列过滤到数据框中

sales_df= df.filter(regex=('Sales*'))

现在我想将它与其他记录合并,但我想将它与 SalesMonth SalesValue 等列合并,在这些列中我将数据转换为 Jan 2000 Feb 3000 等

我追求的输出是

X     Y   ID SalesMonth Sales
xxx yyyy 001 Jan 2000   2000

编辑1:输入文件

ID    Desc       Sales      Sales1     Sales2
                 Month     Month      Month
                 Jan 2000  Feb 2000   Month 2000
 1    Desc1      10         20         30
 1    Desc1      11         21         31
 2    Desc2      7          Nan         0
 3    Desc3     10         20          10 

标签: pythonpandas

解决方案


您需要MultiIndex先在列中创建,然后通过unstack和最后重塑reset_index

print (df)
      Sales    Sales1      Sales2
0  Jan 2000  Feb 2000  Month 2000
1      2000      3000        4000
2      7000      8000        3000

#MultiIndex by first row
df.columns = [df.columns, df.iloc[0]]
#remove first row by indexing - [1:]
df = df.iloc[1:].unstack().reset_index(name='val')
df.columns = ['a','b','c','val']
print (df)
        a           b  c   val
0   Sales    Jan 2000  0  2000
1   Sales    Jan 2000  1  7000
2  Sales1    Feb 2000  0  3000
3  Sales1    Feb 2000  1  8000
4  Sales2  Month 2000  0  4000
5  Sales2  Month 2000  1  3000

如果输入更好,file则使用参数:headerMultiIndex

import pandas as pd

temp=u"""Sales;Sales1;Sales2
Jan 2000;Feb 2000;Month 2000
2000;3000;4000
7000;8000;3000"""
#after testing replace 'pd.compat.StringIO(temp)' to 'filename.csv'
df = pd.read_csv(pd.compat.StringIO(temp), sep=';',header=[0,1])
print (df)

     Sales   Sales1     Sales2
  Jan 2000 Feb 2000 Month 2000
0     2000     3000       4000
1     7000     8000       3000

print (df.columns)
MultiIndex(levels=[['Sales', 'Sales1', 'Sales2'], ['Feb 2000', 'Jan 2000', 'Month 2000']],
           labels=[[0, 1, 2], [1, 0, 2]])

df = df.unstack().reset_index(name='val')
df.columns = ['a','b','c','val']
print (df)
        a           b  c   val
0   Sales    Jan 2000  0  2000
1   Sales    Jan 2000  1  7000
2  Sales1    Feb 2000  0  3000
3  Sales1    Feb 2000  1  8000
4  Sales2  Month 2000  0  4000
5  Sales2  Month 2000  1  3000

推荐阅读