设置pandas DataFrame的索引名称 [英] Set index name of pandas DataFrame

查看:3008
本文介绍了设置pandas DataFrame的索引名称的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个这样的熊猫数据框:

I have a pandas dataframe like this:

    ''     count
sugar      420
milk       108
vanilla    450
...

第一列没有标题,我想给它起一个名字:'ingredient'.

The first column has no header and I would like to give it the name: 'ingredient'.

我从一个csv文件创建了数据框:

I created the dataframe from a csv file:

df = pd.read_csv('./data/file_name.csv', index_col=False, encoding="ISO-8859-1")  
df = df['ingredient_group']  #selecting column 
df = df.value_counts()       #calculating string occurance which return series obj
df = pd.DataFrame(df)        #creating dataframe from series obj

如何为当前没有名称的第一列分配名称成分"?

How do I assign the name 'ingredient' to the first column which has currently no name?

我已经尝试过:

df_count.rename(columns={'': 'ingredient'}, inplace=True)

df = pd.DataFrame(df, columns = ['ingredient','count']

如何防止这种情况发生?

How do I prevent this from happening?

''        count
ingredient  ''
sugar      420
milk       108
vanilla    450
...

推荐答案

如果配料是索引的名称,则可以通过以下方式进行设置:

if ingredients is the name of the index then you can set it by

df.index.name='ingredient'

在当前解决方案中,您已将成分"作为索引的名称,该索引打印在与列名称不同的行中.无法原样更改.请尝试下面的修改后的解决方案,这里索引被复制到具有列名的新列上,并且索引被数字序列替换.

With the current solutions you have 'ingredient' as name of the index, which is printed in different row to that of column names. This cannot be changed as is. Try the modified solution below, here the index is copied on to a new column with column name and the index replaced with sequence of numbers.

df['ingredient']=df.index
df = df.reset_index(drop=True)

这篇关于设置pandas DataFrame的索引名称的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆