Aqua 4
Aqua 4

Reputation: 871

print headers with my dataframe

how do I print my dataframe in such format given below?

Age      Count
25-29    16
<25      16
30-35    16
>35      16
Name: Age, dtype: int64
Press any key to continue . . .

My Output does not have the headers and here is my code

df.columns=['index','District','Group','Age','Holders','Claims']
df.set_index('index',inplace=True)
df_count=df.Age.value_counts()
print(df_count)

here is a part of my csv

"","District","Group","Age","Holders","Claims"
"1","1","<1l","<25",197,38
"2","1","<1l","25-29",264,35
"3","1","<1l","30-35",246,20
"4","1","<1l",">35",1680,156
"5","1","1-1.5l","<25",284,63
"6","1","1-1.5l","25-29",536,84
"7","1","1-1.5l","30-35",696,89
"8","1","1-1.5l",">35",3582,400
"9","1","1.5-2l","<25",133,19
"10","1","1.5-2l","25-29",286,52
"11","1","1.5-2l","30-35",355,74
"12","1","1.5-2l",">35",1640,233
"13","1",">2l","<25",24,4
"14","1",">2l","25-29",71,18
"15","1",">2l","30-35",99,19
"16","1",">2l",">35",452,77
"17","2","<1l","<25",85,22
"18","2","<1l","25-29",139,19
"19","2","<1l","30-35",151,22
"20","2","<1l",">35",931,87
"21","2","1-1.5l","<25",149,25
"22","2","1-1.5l","25-29",313,51
"23","2","1-1.5l","30-35",419,49
"24","2","1-1.5l",">35",2443,290
"25","2","1.5-2l","<25",66,14
"26","2","1.5-2l","25-29",175,46
"27","2","1.5-2l","30-35",221,39
"28","2","1.5-2l",">35",1110,143
"29","2",">2l","<25",9,4
"30","2",">2l","25-29",48,15
"31","2",">2l","30-35",72,12
"32","2",">2l",">35",322,53

Please help me although i get the values but I could not find anything to get the desired output.

PS: i have tried renaming the columns too but its still the same. Thank You.

Upvotes: 1

Views: 1268

Answers (2)

Dheeraj Teta
Dheeraj Teta

Reputation: 51

df.columns=['index','District','Group','Age','Holders','Claims']
df.set_index('index', inplace=True)

To sort in logical order:

So here you want to sort Age with counts.As Age is a string dtype we need to provide a logical order, which can be accomplished by importing CategoricalDtype, so do this :

from pandas.api.types import CategoricalDtype

cat_typ=CategoricalDtype(categories=['<25','25-29','30-35','>35'],ordered=True)             #it will remain in given order when sorted
df['Age']=some['Age'].astype(dtype=cat_typ)

df.count=some['Age'].value_counts(ascending=True).rename_axis('Age').reset_index(name='count')
print(df_count)

output:

     Age  count
0    <25      8
1  25-29      8
2  30-35      8
3    >35      8

Upvotes: 1

jezrael
jezrael

Reputation: 862611

You need rename_axis with reset_index:

df_count=df.Age.value_counts().rename_axis('Age').reset_index(name='Count')

Altrnative solution with rename:

d = {'index':'Age','Age':'Count'}
df_count=df.Age.value_counts().reset_index().rename(columns=d)

Upvotes: 2

Related Questions