1

My script uses pd.read_csv('example.csv') to create data frames in python using pandas. The original CSV files being read only have two columns, but the data frame created by this read_csv method is prepended with sort of an index-like column.

CSV before reading it:

text     100
text     200
text     300
text     400

but after reading it:

         text     100
0        text     200
1        text     300
3        text     400

For the life of me, I can't get rid of that first column. Everything I try instead deletes the second column. I've tried a number of suggestions found online including:

df = df.iloc[: , 1:] (from here)

df = df.drop(df.columns[[0]], axis=1) (from here)

df = df.drop("", 1) from here

For each of those, I either get an error or it removes the second column, leaving me with:

         100
0        200
1        300
3        400

UPDATES:

I have also tried: df = pd.read_csv('example.csv', index_col=False) and I still get the index column.

2 Answers 2

2

When you call df.to_csv() on your constructed DataFrame, pass index=False, like:

df.to_csv('target_file.csv', index=False)

See also the DataFrame.to_csv() doc

Sign up to request clarification or add additional context in comments.

2 Comments

Thanks @sarah-messer, That would be perfect if I were trying to create a csv from a dataframe. I'm trying to create a dataframe from a csv (using read_csv currently). I've tried a few things to include to_csv with no luck.
Ah, by adding the 'index=False' to the point where I create an output file solved it!
0

You should use the following pd.read_csv('example.csv',index_col=False)

1 Comment

Thanks @AJ31. I have also tried that and it still produces an index column

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.