Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I want to get a list of columns names from a pandas pivot table. When I am printing columns of a table i don't get the first one (like in the result below). How can I get a list of all columns?

import pandas as pd
import numpy as np

df = pd.DataFrame({"A": ["foo", "foo", "foo", "foo", "foo",
                         "bar", "bar", "bar", "bar"],
                   "B": ["one", "one", "one", "two", "two",
                         "one", "one", "two", "two"],
                   "C": ["small", "large", "large", "small",
                         "small", "large", "small", "small",
                         "large"],
                   "D": [1, 2, 2, 3, 3, 4, 5, 6, 7],
                   "E": [2, 4, 5, 5, 6, 6, 8, 9, 9]})

df_table = pd.pivot_table(df,index=['A'], values='D', columns=['C'], aggfunc=np.sum)
print(df_table)
print(list(df_table.columns))

the result:

C    large  small
A                
bar     11     11
foo      4      7

['large', 'small']

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
341 views
Welcome To Ask or Share your Answers For Others

1 Answer

I think you're missing the reset_index()

df_table = pd.pivot_table(df,index=['A'], values='D', columns=['C'], aggfunc=np.sum).reset_index()
print(df_table)
print(list(df_table.columns))

output:

print(list(df_table.columns))
['A', 'large', 'small']

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...