【问题标题】:Dropping index in DataFrame for CSV file删除 CSV 文件的 DataFrame 中的索引
【发布时间】:2021-04-14 07:07:23
【问题描述】:

在 PyCharm 中处理 CSV 文件。我想删除自动生成的索引列。但是,当我打印它时,我在终端中得到的答案是“无”。其他用户的所有回答都表明 reset_index 方法应该可以工作。

如果我只是说“df = df.reset_index(drop=True)”,它也不会删除该列。

import pandas as pd
df = pd.read_csv("music.csv")
df['id'] = df.index + 1
cols = list(df.columns.values)
df = df[[cols[-1]]+cols[:3]]
df = df.reset_index(drop=True, inplace=True)
print(df)

【问题讨论】:

  • 不能删除 pandas 数据框中的索引
  • reset_index(drop=True) 通常在对希望删除原始索引的数据帧进行排序后使用。 reset_index 本身会重置索引以匹配新排序的项目。

标签: python pandas dataframe indexing


【解决方案1】:

我同意@It_is_Chris。还有,

这不是真的,因为 return 是 None:

df = df.reset_index(drop=True, inplace=True)

应该是这样的:

df.reset_index(drop=True, inplace=True)

df = df.reset_index(drop=True)

【讨论】:

    【解决方案2】:

    既然你说你正在尝试"delete the automatically-generated index column",我可以想到两个解决方案!

    拳头解决方案:

    将索引列分配给您的数据集索引列。假设您的数据集已经被索引/编号,那么您可以执行以下操作:

    #assuming your first column in the dataset is your index column which has the index number of zero  
    df = pd.read_csv("yourfile.csv", index_col=0)
    
    #you won't see the automatically-generated index column anymore
    df.head()
    

    第二种解决方案:

    您可以在最终的 csv 中删除它:

    #To export your df to a csv without the automatically-generated index column
    df.to_csv("yourfile.csv", index=False)  
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-04-17
      • 1970-01-01
      • 2023-01-25
      • 2018-07-04
      • 2014-09-11
      • 2017-03-25
      • 2012-08-14
      • 2023-04-05
      相关资源
      最近更新 更多