EdgeDev
EdgeDev

Reputation: 2486

How to remove Pandas Index Column when Writting to CSV

Read in CSV string file:

data = pd.read_csv(data, sep=',')

Sorted it in alphabetical order:

 data = data.sort_values("Package", inplace = False)

Reseted the Index:

data = data.reset_index()

Turned off Indexing while writing to CSV:

data.to_csv("combined.csv", index=False)

The Result:

enter image description here

Upvotes: 2

Views: 4229

Answers (3)

EdgeDev
EdgeDev

Reputation: 2486

data is a string formatted for csv. Solution was to save it to csv files before using pandas to drop the index column as demonstrated below:

def create_file(data, file_name):
   f = open(file_name, "w", encoding="utf-8")
   f.write(data)
   f.close()

create_file(data,  "combined.csv")

data = pd.read_csv("combined.csv", sep=',')
data = data.sort_values("Package", inplace = False)
data.to_csv("combined.csv", index = False)

Upvotes: 1

Aaron Meese
Aaron Meese

Reputation: 2213

According to this thread, the problem can normally be avoided by skipping calling reset_index.

If that doesn't work for you, one alternative solution that was offered is to try the following:

df.to_csv(' file_name.csv ')
df_new = pd.read_csv('file_name.csv').drop(['unnamed 0'],axis=1)

Upvotes: 0

user19362910
user19362910

Reputation:

data = data.reset_index(drop=True)

Upvotes: 0

Related Questions