Reputation: 53
I would like to be able to flip a csv file rows but keep the headers.
timestamp open high low close volume
2020-04-14 2805.1001 2851.8501 2805.1001 2846.0601 3113388741
2020-04-13 2782.4600 2782.4600 2721.1699 2761.6299 5274310000
.....
2000-01-04 1455.2200 1455.2200 1397.4301 1399.4200 1009000000
2000-01-03 1469.2500 1478.0000 1438.3600 1455.2200 931800000
timestamp open high low close volume
2000-01-03 1469.2500 1478.0000 1438.3600 1455.2200 931800000
2000-01-04 1455.2200 1455.2200 1397.4301 1399.4200 1009000000
.....
2020-04-13 2782.4600 2782.4600 2721.1699 2761.6299 5274310000
2020-04-14 2805.1001 2851.8501 2805.1001 2846.0601 3113388741
I have been able to flip the data over with this, but I cannot retain the headers. Skip headers is added, else the headers are put on the bottom of the csv file.
def reverse_csv():
with open("spx.csv", "r") as infile, open("spx_cleaned.csv", "w") as outfile:
reader = csv.reader(infile)
next(reader, None) # skip the headers
writer = csv.writer(outfile)
for row in reversed(list(reader)):
# process each row
writer.writerow(row)
Thanks!
Upvotes: 2
Views: 585
Reputation: 19957
Can you try the following?
pd.read_csv('input.csv').iloc[::-1].to_csv('output.csv', index=False)
Upvotes: 2
Reputation: 202
Try
import pandas as pd
df = pd.read_csv('spx.csv')
df = df[::-1].reset_index(drop=True)
df.to_csv('spx_cleaned.csv')
Upvotes: 0