簡體   English   中英

刪除 CSV 文件的 DataFrame 中的索引

[英]Dropping index in DataFrame for CSV file

使用 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)

我同意@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)

既然您說您正在嘗試"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)  

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM