簡體   English   中英

如何為具有 1 個或多個列的 Pandas pivot 表保留或顯示值的列名?

[英]How do I keep or show a value's column name for a Pandas pivot table that has 1 or more columns?

當我使用 Pandas 創建包含列的 pivot 表時,生成的 pivot 中的列應該與值命名相同,但沒有列名。 In the following example, the pivot table's value is based on column C, but when the pivot table is output as text or HTML the column has no header. 有沒有辦法讓 pandas 保留或顯示該列的列名 - 應該命名為 C?

import pandas as pd
import numpy as np
df = pd.DataFrame(
        {
            "A": ["one", "one", "two", "three"] * 3,
            "B": ["foo", "foo", "foo", "bar", "bar", "bar"] * 2,
            "C": np.random.randn(12),
        }
    )

pivot = pd.pivot_table(df, values="C", index=["A"], columns=["B"])
print(pivot)
print(pivot.to_html())

output 作為文本是:

B           bar       foo
A                        
one    0.445356 -0.026072
three -0.336463 -0.717296
two    0.436955 -0.789914

但是,我希望 C 位於包含 C 聚合的 2 列的 2 個標題中,例如 0.445356 -0.026072 正上方的空格,如下所示:

B           bar       foo
A             C         C
one    0.445356 -0.026072
three -0.336463 -0.717296
two    0.436955 -0.789914

output 作為 html 是:

<table border="1" class="dataframe">
  <thead>
    <tr style="text-align: right;">
      <th>B</th>
      <th>bar</th>
      <th>foo</th>
    </tr>
    <tr>
      <th>A</th>
      <th></th>
      <th></th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <th>one</th>
      <td>0.445356</td>
      <td>-0.026072</td>
    </tr>
    <tr>
      <th>three</th>
      <td>-0.336463</td>
      <td>-0.717296</td>
    </tr>
    <tr>
      <th>two</th>
      <td>0.436955</td>
      <td>-0.789914</td>
    </tr>
  </tbody>
</table>

但是我希望它是:

<table border="1" class="dataframe">
  <thead>
    <tr style="text-align: right;">
      <th>B</th>
      <th>bar</th>
      <th>foo</th>
    </tr>
    <tr>
      <th>A</th>
      <th>C</th>
      <th>C</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <th>one</th>
      <td>0.445356</td>
      <td>-0.026072</td>
    </tr>
    <tr>
      <th>three</th>
      <td>-0.336463</td>
      <td>-0.717296</td>
    </tr>
    <tr>
      <th>two</th>
      <td>0.436955</td>
      <td>-0.789914</td>
    </tr>
  </tbody>
</table>

嘗試assign一個新列

out = pd.pivot_table(df.assign(key='C'), values="C", index=["A"], columns=["B",'key'])
B           bar       foo
key           C         C
A                        
one    0.838796  1.029971
three  0.395790  1.192384
two   -0.583045  0.264484

暫無
暫無

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

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