gpt4 book ai didi

python - 设置 pandas DataFrame 的索引名称

转载 作者:太空狗 更新时间:2023-10-29 20:10:37 26 4
gpt4 key购买 nike

我有一个像这样的 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
...

最佳答案

如果成分是索引的名称,那么您可以通过以下方式设置它

df.index.name='ingredient'

使用当前的解决方案,您将“成分”作为索引的名称,它与列名打印在不同的行中。这不能按原样更改。尝试下面修改后的解决方案,这里将索引复制到具有列名的新列上,并将索引替换为数字序列。

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

关于python - 设置 pandas DataFrame 的索引名称,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37968730/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com