熊猫数据透视表列名称和值列名称要删除

时间:2020-06-27 18:26:54

标签: python pandas

我有一个输入df

{'Name': {0: 'AA',1: 'BB',2: 'CC',3: 'DD',4: 'EE',5: 'AA',6: 'EE',7: 'FF'},
 'WK': {0: 1, 1: 2, 2: 3, 3: 4, 4: 2, 5: 3, 6: 4, 7: 5},
 'LG': {0: 'qwe',1: 'wer',2: 'sff',3: 'err',4: 'wer',5: 'rtt',6: 'eww',7'tyy'}}

enter image description here

我做了以下

df1=pd.pivot_table(dfp,values=['LG'],index='Name',columns='WK',aggfunc='count').fillna(0)

enter image description here

我希望不显示以下输出..像WK和LG一样,WK值作为列

enter image description here

列应类似于名称1 2 3 4 5

2 个答案:

答案 0 :(得分:3)

您可以尝试一下。将if let dictionary = snapshot.value as? [String: AnyObject] { ... 作为'LG'而不是str传递。

list

(df.pivot_table(index='Name', columns='WK', values='LG', aggfunc = 'count', fill_value=0).
    rename_axis(index=None, columns=None))

    1  2  3  4  5
AA  1  0  1  0  0
BB  0  1  0  0  0
CC  0  0  1  0  0
DD  0  0  0  1  0
EE  0  1  0  1  0
FF  0  0  0  0  1

您可以使用pd.crosstab

(df.pivot_table(index='Name', columns='WK', aggfunc = 'size', fill_value=0).
    rename_axis(index=None, columns=None))

GroupBy.sizedf.unstack一起使用

pd.crosstab(index = df['Name'], columns = df['WK']).rename_axis(index=None, columns=None)

    1  2  3  4  5
AA  1  0  1  0  0
BB  0  1  0  0  0
CC  0  0  1  0  0
DD  0  0  0  1  0
EE  0  1  0  1  0
FF  0  0  0  0  1
  • 如果您只想隐藏列的名称而不是索引的名称,请从.rename_axis中删除df.groupby(['Name', 'WK']).size().unstack(fill_value=0) WK 1 2 3 4 5 Name AA 1 0 1 0 0 BB 0 1 0 0 0 CC 0 0 1 0 0 DD 0 0 0 1 0 EE 0 1 0 1 0 FF 0 0 0 0 1

答案 1 :(得分:0)

只需要对列和索引名进行一些后期处理。删除“ LG”级别(或者,因为只使用一个,所以将其作为字符串而不是列表传递),删除“ WK”作为列级别名称。如果您想将“名称”作为索引而不是列,请取出.reset_index()

df = pd.DataFrame({'Name':"AA,BB,CC,DD,EE,AA,EE,FF".split(','), 'WK':[1,2,3,4,2,3,4,5], 'LG':np.ones(8)})

df1=pd.pivot_table(df,values=['LG'],index='Name',columns='WK',aggfunc='count').fillna(0)

#~ Drop the LG, make Name into a columns, then drop WK as column level name
df1 = df1.droplevel(0,axis=1).reset_index().rename_axis(columns=None)

      Name    1    2    3    4    5
#~    0   AA  1.0  0.0  1.0  0.0  0.0
#~    1   BB  0.0  1.0  0.0  0.0  0.0
#~    2   CC  0.0  0.0  1.0  0.0  0.0
#~    3   DD  0.0  0.0  0.0  1.0  0.0
#~    4   EE  0.0  1.0  0.0  1.0  0.0
#~    5   FF  0.0  0.0  0.0  0.0  1.0
相关问题