簡體   English   中英

python - 添加每個組上方的每個組的名稱

[英]python - add name of each group above each group

我有一個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

您可以使用帶有keys參數的concat

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM