Konstantin
Konstantin

Reputation: 3159

What is DataFrame.columns.name?

Could you explain to me, what the purpose of the 'DataFrame.columns.name' attribute is?

I unintentionally got it after creating a pivot table and resetting the index.

import pandas as pd

df = pd.DataFrame(['a', 'b'])
print(df.head())

# OUTPUT:
#    0
# 0  a
  1  b

df.columns.name = 'temp'
print(df.head())

# OUTPUT:
# temp  0
# 0     a
# 1     b

Upvotes: 13

Views: 15284

Answers (1)

Steven G
Steven G

Reputation: 17122

giving name to column levels could be useful in many ways when you manipulate your data.

a simple example would be when you use `stack()'

df = pd.DataFrame([['a', 'b'], ['d', 'e']], columns=['hello', 'world'])
print(df.stack())
0  hello    a
   world    b
1  hello    d
   world    e
df.columns.name = 'temp'
print(df.stack())
    temp 
0  hello    a
   world    b
1  hello    d
   world    e
dtype: object

as you can see the stacked df has kept the level name of the columns. in a multi-index / multi-level dataframe this could be very useful

slightly more complex example (from the doc):

tuples = [('bar', 'one'),
          ('bar', 'two'),
          ('baz', 'one'),
          ('baz', 'two'),
          ('foo', 'one'),
          ('foo', 'two'),
          ('qux', 'one'),
          ('qux', 'two')]

index = pd.MultiIndex.from_tuples(tuples, names=['first', 'second'])
pd.MultiIndex(levels=[['bar', 'baz', 'foo', 'qux'], ['one', 'two']],
           labels=[[0, 0, 1, 1, 2, 2, 3, 3], [0, 1, 0, 1, 0, 1, 0, 1]],
           names=['first', 'second'])

s = pd.Series(np.random.randn(8), index=index)
print(s)
first  second
bar    one      -0.9166
       two      1.0698 
baz    one      -0.8749
       two      1.3895 
foo    one      0.5333 
       two      0.1014 
qux    one      -1.2350
       two      -0.6479
dtype: float64

s.unstack()
second     one     two
first                 
bar    -0.9166 1.0698 
baz    -0.8749 1.3895 
foo    0.5333  0.1014 
qux    -1.2350 -0.6479

Upvotes: 3

Related Questions