我有一个 csv 文件,其中包含几只股票的严重值,如下所示:
date stock_A date stock_B date stock_C
30.10.2017 09:00 3223 30.10.2017 09:00 53234 ... .....
30.10.2017 09:02 2544 30.10.2017 09:01 24337 ... .....
30.10.2017 09:04 925 30.10.2017 09:02 4529 ... .....
30.10.2017 09:05 3210 30.10.2017 09:03 8534 ... .....
如您所见,每隔一列就是一个日期时间索引。然而,它的顺序/频率不同。有没有一种方法可以用 pandas 导入这些数据,以便我只获得一个索引并相应地映射数据?
我已经尝试过这段代码:
pd.read_csv(file, sep=";", header=0, index_col=['date'], parse_dates=True, dtype=object)
但它只导入第一行作为索引,其他日期作为包含值的列。但是,我希望我的 DataFrame 如下:
date stock_A stock_B stock_C
30.10.2017 09:00 3223 53234 122
30.10.2017 09:01 0 24337 1215
30.10.2017 09:02 2544 4529 0
30.10.2017 09:03 0 8534 1354
...
最佳答案
使用 concat
的列表理解和 set_index
对于每对 DatetimeIndex
:
df = pd.read_csv(file, sep=";")
a = df.columns[::2]
b = df.columns[1::2]
df=pd.concat([df[[j]].set_index(pd.to_datetime(df[i])) for i, j in zip(a,b)],axis=1).fillna(0)
print (df)
stock_A stock_B
2017-10-30 09:00:00 3223.0 53234.0
2017-10-30 09:01:00 0.0 24337.0
2017-10-30 09:02:00 2544.0 4529.0
2017-10-30 09:03:00 0.0 8534.0
2017-10-30 09:04:00 925.0 0.0
2017-10-30 09:05:00 3210.0 0.0
索引中的最后一列:
df = df.rename_axis('date').reset_index()
print (df)
date stock_A stock_B
0 2017-10-30 09:00:00 3223.0 53234.0
1 2017-10-30 09:01:00 0.0 24337.0
2 2017-10-30 09:02:00 2544.0 4529.0
3 2017-10-30 09:03:00 0.0 8534.0
4 2017-10-30 09:04:00 925.0 0.0
5 2017-10-30 09:05:00 3210.0 0.0
关于python - pandas read_csv 每隔一列都有索引,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50326464/