AlphaWolf
AlphaWolf

Reputation: 405

Create label for two column in pandas

I have a pandas dataframe with two column of data. Now i want to make a label for two column, like the picture bellow: enter image description here

Because two column donot have the same value so cant use groupby. I just only want add the label AAA like that. So, how to do it? Thank you

Upvotes: 3

Views: 2187

Answers (2)

jezrael
jezrael

Reputation: 862511

If need create MultiIndex in columns, simpliest is:

df.columns = [['AAA'] * len(df.columns), df.columns]

It is similar as MultiIndex.from_arrays, also is possible add names parameter:

n = ['a','b']
df.columns = pd.MultiIndex.from_arrays([['AAA'] * len(df.columns), df.columns], names=n)

Upvotes: 3

piRSquared
piRSquared

Reputation: 294218

reassign to the columns attribute with an newly constructed pd.MultiIndex

df.columns = pd.MultiIndex.from_product([['AAA'], df.columns.tolist()])

Consider the dataframe df

df = pd.DataFrame(1, ['hostname', 'tmserver'], ['value', 'time'])
print(df)

          value  time
hostname      1     1
tmserver      1     1

Then

df.columns = pd.MultiIndex.from_product([['AAA'], df.columns.tolist()])

print(df)

           AAA     
         value time
hostname     1    1
tmserver     1    1

Upvotes: 5

Related Questions