我想将列索引设置为Date,但是不知道做错了什么,代码和数据集的第一部分在下面。
代码:
from random import randint
import pandas_datareader.data as web
import pandas as pd
import datetime
import itertools as it
import numpy as np
import csv
start = datetime.datetime(1984, 9, 11)
end = datetime.datetime(2019, 4, 2)
df = pd.read_csv('C:Users\GrahamFam\Desktop\Data Archive\Daily3eve(Archive).txt')
df.columns = ['Date','B1','B2','B3']
df.set_index('Date')
print(df)
熊猫数据:
Date B1 B2 B3
0 4022019 7 2 7
1 4012019 3 8 9
2 3312019 5 6 5
3 3302019 9 4 6
4 3292019 4 6 2
5 3282019 1 1 1
6 3272019 0 6 9
7 3262019 9 1 1
8 3252019 9 9 1
9 3242019 3 6 6
我也想翻转数据,所以旧数据在前,新数据在后。
答案 0 :(得分:2)
让pd.read_csv
做些繁重的事情。
import pandas as pd
import csv
import sys
if sys.version_info[0] < 3:
from StringIO import StringIO
else:
from io import StringIO
csvdata = StringIO("""
i,Date,B1,B2,B3
0,4022019,7,2,7
1,4012019,3,8,9
2,3312019,5,6,5
3,3302019,9,4,6
4,3292019,4,6,2
5,3282019,1,1,1
6,3272019,0,6,9
7,3262019,9,1,1
8,3252019,9,9,1
9,3242019,3,6,6
""")
df = pd.read_csv(csvdata, sep=",", index_col="Date", parse_dates=True, infer_datetime_format=True)
#df.columns = ['B1','B2']
print(df)
i B1 B2 B3
Date
4022019 0 7 2 7
4012019 1 3 8 9
3312019 2 5 6 5
3302019 3 9 4 6
3292019 4 4 6 2
3282019 5 1 1 1
3272019 6 0 6 9
3262019 7 9 1 1
3252019 8 9 9 1
3242019 9 3 6 6
答案 1 :(得分:1)
from random import randint
import pandas_datareader.data as web
import pandas as pd
import datetime
import itertools as it
import numpy as np
import csv
start = datetime.datetime(1984, 9, 11)
end = datetime.datetime(2019, 4, 2)
df = pd.read_csv('C:Users\GrahamFam\Desktop\Data Archive\Daily3eve(Archive).txt')
df.columns = ['Date','B1','B2','B3']
#You have to assign it to the df
df = df.set_index('Date')
print(df)