python在每个组上面添加每个组的名称

2024-05-14 22:26:44 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个excel文件,其中按行列出示例,按列列出属性。 我使用python将样本按一个或多个属性分组,并使用xlsxwriter导出。 有没有办法在分组上方的行中自动插入每个分组的标题?你知道吗

type1 = ['a', 'c', 'e']
t1 = result.loc[df['Name'].isin(type1)]

type2 = ['b','f']
t2 = result.loc[df['Name'].isin(type2)]

group_by_type = [t1, t2]

编辑

      Attribute1         Attribute2          Attribute3  Calculation1
0              1.565417  102.975496                    a -0.348246
1              1.577817  129.019182                    b -0.984943
2              1.577817  145.013103                    c -0.624412
3              1.594367  158.924852                    d -0.701562
4              1.586100  159.029720                    e -0.436547
5              1.594367  160.920870                    f -0.664863
6              1.586100  161.045205                    g  0.856694
7              1.598500  204.981242                    h -0.547259
8              1.619200  173.009131                    i -0.583041
9              1.623333  175.024768                    j -0.640267

type1 = ['a', 'c', 'e']
t1 = result.loc[df['Attribute3'].isin(type1)]

type2 = ['b','f']
t2 = result.loc[df['Attribute3'].isin(type2)]

titles = ['title1', 'title2']

result2 = pd.concat([t1, t2], keys=titles, axis=0)

print(result2[0:10])

             Attribute1         Attribute2          Attribute3  Calculation1
title1 0              1.565417  102.975496                    a -0.348246
       2              1.577817  145.013103                    c -0.624412
       4              1.586100  159.029720                    e -0.436547
title2 1              1.577817  129.019182                    b -0.984943
       5              1.594367  160.920870                    f -0.664863

Tags: namedf属性resultloct1t2isin
1条回答
网友
1楼 · 发布于 2024-05-14 22:26:44

可以将concatkeys参数一起使用:

np.random.seed(0)
df1 = pd.DataFrame(np.random.choice(10, (3, 3)), columns=list('ABC'))
df2 = pd.DataFrame(np.random.choice(10, (3, 3)), columns=list('DEF'))

titles = ['first', 'second']
pd.concat([df1, df2], keys=titles, axis=1)

  first       second      
      A  B  C      D  E  F
0     5  0  3      4  7  6
1     3  7  9      8  8  1
2     3  5  2      6  7  7

相关问题 更多 >

    热门问题