Skip to main content
 首页 » 编程设计

python之DATE 和 TIME 列的简单索引

2024年10月17日8sky-heaven

我有一个包含如下数据的 CSV:

<DATE>      <TIME>    <OPEN>  <LOW>  <HIGH>  <CLOSE>   
2001-01-03  00:00:00  0.9507  0.9505  0.9509  0.9506   
....    
2015-05-13  02:00:00  0.9496  0.9495  0.9509  0.9505 

我想在 和

由于数据存储在 CSV 中,我不确定在创建数据框之前如何将 2 列(DATE 和 TIME)解析为一列。

我看过很多答案,但它们似乎对我想做的事情很费解,而且我确信我错过了简单的解决方案

Context around what lead me to this: 

我确定设置新值的正确方法(当我计算滚动平均值时)是:

df.set_value('index', 'column', value) 

因为我的索引当前是最新的,引用特定行(比如第一行)的索引意味着设置了很多值而不是一个

请您参考如下方法:

更新:

In [170]: df = pd.read_csv('/path/to/file.csv', parse_dates={'TIMESTAMP': ['DATE','TIME']}).set_index('TIMESTAMP') 
 
In [171]: df 
Out[171]: 
                       OPEN     LOW    HIGH   CLOSE 
TIMESTAMP 
2001-01-03 00:00:00  0.9507  0.9505  0.9509  0.9506 
2001-01-03 01:00:00  0.9507  0.9505  0.9509  0.9506 
2001-01-03 02:00:00  0.9507  0.9505  0.9509  0.9506 
2001-01-03 03:00:00  0.9507  0.9505  0.9509  0.9506 
2001-01-03 04:00:00  0.9507  0.9505  0.9509  0.9506 
2001-01-04 00:00:00  0.9507  0.9505  0.9509  0.9506 
2001-01-04 01:00:00  0.9507  0.9505  0.9509  0.9506 
2001-01-04 02:00:00  0.9507  0.9505  0.9509  0.9506 
 
In [172]: df.index.dtype 
Out[172]: dtype('<M8[ns]') 

旧答案:

你可以这样做:

In [155]: df 
Out[155]: 
   a  b  c 
0  0  0  3 
1  1  2  0 
2  2  2  3 
3  1  0  0 
4  1  3  2 
5  4  0  1 
6  2  0  3 
7  2  1  2 
8  3  3  4 
9  0  0  3 
 
In [156]: df.join(df.iloc[:, :2], rsuffix='_idx').set_index((df.iloc[:, :2].columns + '_idx').tolist()) 
Out[156]: 
             a  b  c 
a_idx b_idx 
0     0      0  0  3 
1     2      1  2  0 
2     2      2  2  3 
1     0      1  0  0 
      3      1  3  2 
4     0      4  0  1 
2     0      2  0  3 
      1      2  1  2 
3     3      3  3  4 
0     0      0  0  3 

但是,您实际上并不需要它,因为它是多余的 - 您的数据仍在索引中并且可以使用它...


更新: 从 Pandas 0.20.1 开始 the .ix indexer is deprecated, in favor of the more strict .iloc and .loc indexers .