用我的数据框打印标题

时间:2018-01-13 07:21:49

标签: python pandas

如何以下面给出的格式打印我的数据框?

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

我的输出没有标题,这是我的代码

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

这是我的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

请帮助我,虽然我得到了值但我找不到任何东西来获得所需的输出。

  

PS:我也试过重命名列,但它仍然是相同的。   谢谢。

2 个答案:

答案 0 :(得分:2)

rename_axis需要reset_index

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

rename的替代解决方案:

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

答案 1 :(得分:1)

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

按逻辑顺序排序:

因此,您希望对Age进行排序。由于Age是字符串dtype,我们需要提供逻辑顺序,这可以通过导入{{}来完成1}},所以这样做:

CategoricalDtype

输出:

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)