简体   繁体   中英

How to delete or drop the column labelled “index” from a dataframe when using to_csv() to save as csv

I am reading a csv file, cleaning it up a little, and then saving it back to a new csv file. The problem is that the new csv file has a new column (first column in fact), labelled as index . Now this is not the row index, as I have turned that off in the to_csv() function as you can see in the code. Plus row index doesn't have a column label as well.

df = pd.read_csv('D1.csv', na_values=0, nrows = 139)    # Read csv, with 0 values converted to NaN
df = df.dropna(axis=0, how='any')                       # Delete any rows containing NaN
df = df.reset_index()
df.to_csv('D1Clean.csv', index=False)

Any ideas where this phantom column is coming from and how to get rid of it?

I think you need add parameter drop=True to reset_index :

df = df.reset_index(drop=True)

drop : boolean, default False

Do not try to insert index into dataframe columns. This resets the index to the default integer index.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM