我希望能够翻转 csv 文件行但保留标题。
当前
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
我已经能够用这个翻转数据,但我无法保留标题。添加跳过标题,否则标题将放在 csv 文件的底部。
当前代码
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)
谢谢!
最佳答案
你能尝试以下方法吗?
pd.read_csv('input.csv').iloc[::-1].to_csv('output.csv', index=False)
关于python - 如何在保留标题的同时翻转 csv 行顺序?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61240634/