Python 设置 pandas DataFrame 的索引名称
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/37968730/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Set index name of pandas DataFrame
提问by Afke
I have a pandas dataframe like this:
我有一个像这样的熊猫数据框:
'' count
sugar 420
milk 108
vanilla 450
...
The first column has no header and I would like to give it the name: 'ingredient'.
第一列没有标题,我想给它起个名字:“成分”。
I created the dataframe from a csv file:
我从一个 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
How do I assign the name 'ingredient' to the first column which has currently no name?
如何将名称“成分”分配给当前没有名称的第一列?
I already tried:
我已经尝试过:
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
...
回答by user3404344
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.
使用当前的解决方案,您将 'ingredient' 作为索引名称,它打印在与列名称不同的行中。这不能按原样更改。尝试下面修改后的解决方案,这里将索引复制到一个带有列名的新列上,并用数字序列替换索引。
df['ingredient']=df.index
df = df.reset_index(drop=True)
回答by Dmitry Andreev
Try this:
尝试这个:
cols_ = df.columns
cols[0] = 'ingredient'
df.columns = cols_