设置pandas DataFrame的索引名称

时间:2016-06-22 12:57:00

标签: python csv pandas dataframe

我有一个像这样的pandas数据框:

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

第一列没有标题,我想给它起名称:'ingredient'。

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

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

如何将名称'ingredient'分配给当前没有名称的第一列?

我已经尝试过:

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

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

如何防止这种情况发生?

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

3 个答案:

答案 0 :(得分:12)

如果成分是索引的名称,那么您可以通过

进行设置
df.index.name='ingredient'

使用当前的解决方案,您拥有'成分'作为索引的名称,它与列名称的行不同地打印。这不能改变。尝试下面的修改后的解决方案,此处将索引复制到具有列名称的新列,并将索引替换为数字序列。

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

答案 1 :(得分:3)

您正在寻找如何为索引设置 AXIS 的名称“成分”。

    df.rename_axis('ingredient', inplace=True)

答案 2 :(得分:1)

试试这个:

cols_ = df.columns
cols[0] = 'ingredient'
df.columns = cols_