簡體   English   中英

Python 3:轉置 Pandas 數據幀/“熔化”數據幀的列

[英]Python 3: Transpose columns of Pandas Data Frame / "melt" data frame

我有一個像這樣的 Pandas 數據框:

    uid   category   count
0    1     comedy     5
1    1     drama      7
2    2     drama      4
3    3     other      10    
4    3     comedy     6

除了有幾十個類別、幾百萬行和幾十個其他列。

我想把它變成這樣的東西:

    id   cat_comedy   cat_drama    cat_other
0    1    5            7            0
1    2    0            4            0
2    3    6            0            10

我不知道如何做到這一點,正在尋找提示/提示/完整的解決方案。 我真的不關心行索引。

謝謝。

我認為這就是您所追求的(該操作稱為“樞軸”):

from pandas import DataFrame

df = DataFrame([
    {'id': 1, 'category': 'comedy', 'count': 5},
    {'id': 1, 'category': 'drama', 'count': 7},
    {'id': 2, 'category': 'drama', 'count': 4},
    {'id': 3, 'category': 'other', 'count': 10},
    {'id': 3, 'category': 'comedy', 'count': 6}
]).set_index('id')

result = df.pivot(columns=['category'])

print(result)

結果:

          count
category comedy drama other
id
1           5.0   7.0   NaN
2           NaN   4.0   NaN
3           6.0   NaN  10.0

針對您的評論,如果您不希望id作為df的索引,您可以告訴操作將其用作 pivot 的索引。 您需要pivot_table而不是pivot來實現這一點,因為它允許處理一個旋轉索引/列對的重復值。

用零替換NaN也是一種選擇:


df = DataFrame([
    {'uid': 1, 'category': 'comedy', 'count': 5},
    {'uid': 1, 'category': 'drama', 'count': 7},
    {'uid': 2, 'category': 'drama', 'count': 4},
    {'uid': 3, 'category': 'other', 'count': 10},
    {'uid': 3, 'category': 'comedy', 'count': 6}
])

result = df.pivot_table(columns=['category'], index='uid', fill_value=0)

print(result)

但是,請注意,結果表仍將uid作為其索引。 如果這不是您想要的,您可以將結果列恢復為正常列:

result = df.pivot_table(columns=['category'], index='uid', fill_value=0).reset_index()

最終結果:

         uid  count
category     comedy drama other
0          1      5     7     0
1          2      0     4     0
2          3      6     0    10

@Grismar 的原始答案(因為他首先得到它而被贊成)非常接近,但不太奏效。 不要在 pivot 調用之前重置索引,然后執行以下操作:

df2 = df.pivot_table(columns='category', index='uid', aggfunc=sum)
df2 = df2.fillna(0).reset_index()

df2 現在是您想要的 dataframe。 fillna function 將所有NaNs替換為0s

使用pivot_table完整解決方案:

import pandas as pd

df = pd.DataFrame([
    {'uid': 1, 'category': 'comedy', 'count': 5},
    {'uid': 1, 'category': 'drama', 'count': 7},
    {'uid': 2, 'category': 'drama', 'count': 4},
    {'uid': 3, 'category': 'other', 'count': 10},
    {'uid': 3, 'category': 'comedy', 'count': 6}
])

df.pivot_table(
    columns='category', 
    index='uid', 
    aggfunc=sum, 
    fill_value=0
)

暫無
暫無

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

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