Reputation:
When I iterate this code over, pandas keeps creating new index columns in my csv.
import pandas as pd
credentials = pd.read_csv("credentials.csv")
email = "[email protected]"
nick = "jarda"
passw = "heslo"
csfd_conf_link = "test.link"
dict_to_append = {"nick": nick, "pass": passw, "email": email, "conf_link": csfd_conf_link}
credentials_updated = credentials.append(dict_to_append, ignore_index=True)
credentials_updated.to_csv("credentials.csv")
So it ends up looking like this this (better visible in the screenshot):
Unnamed: 0 Unnamed: 0.1 ... email conf_link
0 0 0.0 ... [email protected] test
1 1 1.0 ... [email protected] test
2 2 2.0 ... [email protected] https://www.csfd.cz/potvrzeni/registration/?co...
3 3 3.0 ... [email protected] test.link
4 4 4.0 ... [email protected] test.link
5 5 5.0 ... [email protected] test.link
6 6 NaN ... [email protected] test.link
I know that indexing can be turned of with credentials_updated.to_csv("credentials.csv", index=False)
. However, what if I wanted to have the columns indexed?
Any help would be appreciated. Thanks.
Upvotes: 0
Views: 541
Reputation: 13417
If you want to keep the Index
roundtrip, you can specify index_col
in your call to pd.read_csv, and keep index=True
in your call to to_csv
:
import pandas as pd
try:
credentials = pd.read_csv("credentials.csv", index_col=0)
except FileNotFoundError:
credentials = pd.DataFrame()
...
credentials_updated.to_csv("credentials.csv")
The try/except will help you out if you delete your "credentials.csv"
for whatever reason.
Upvotes: 1