Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to add columns label on a Pandas DataFrame

Tags:

python

pandas

I can't understand how can I add column names on a pandas dataframe, an easy example will clarify my issue:

dic = {'a': [4, 1, 3, 1], 'b': [4, 2, 1, 4], 'c': [5, 7, 9, 1]}
df = pd.DataFrame(dic)

now if I type df than I get

   a  b  c
0  4  4  5
1  1  2  7
2  3  1  9
3  1  4  1

say now that I generate another dataframe just by summing up the columns on the previous one

a = df.sum()

if I type 'a' than I get

a     9
b    11
c    22

That looks like a dataframe without with index and without names on the only column. So I wrote

a.columns = ['column']

or

a.columns = ['index', 'column']

and in both cases Python was happy because he didn't provide me any message of errors. But still if I type 'a' I can't see the columns name anywhere. What's wrong here?

like image 964
Stefano Fedele Avatar asked Jul 29 '16 09:07

Stefano Fedele


People also ask

How do I add a column label to a DataFrame?

You can add header to pandas dataframe using the df. colums = ['Column_Name1', 'column_Name_2'] method. You can use the below code snippet to set column headers to the dataframe.

How do I get column labels in Pandas?

To get the column names in Pandas dataframe you can type <code>print(df. columns)</code> given that your dataframe is named “df”.


1 Answers

The method DataFrame.sum() does an aggregation and therefore returns a Series, not a DataFrame. And a Series has no columns, only an index. If you want to create a DataFrame out of your sum you can change a = df.sum() by:

a = pandas.DataFrame(df.sum(), columns = ['whatever_name_you_want'])
like image 88
ysearka Avatar answered Sep 20 '22 22:09

ysearka