pandas 入门二

if __name__ == '__main__':
    file_path = os.getcwd() + '/configure.csv'
    print file_path
    st = pd.read_csv(file_path)  # 读取策略文件
    # 数据转换
    st_transform = st.set_index('strategy').stack().reset_index()
    # print st_transform
    st_transform.columns = ['strategy', 'index', 'value']  # 文件转换为,策略,指标,指标值三列
    print st_transform
configure.csv

strategy,t1,t2,t3,t4
strategy1,0.3,1.0,0.2,0.9
strategy2,0.4,0.8,0.22,0.95
strategy3,0.32,0.90,0.25,0.96
strategy4,0.34,0.88,0.28,0.97

 

结果
strategy             index  value
0   strategy1  t1   0.30
1   strategy1  t2   1.00
2   strategy1     t3   0.20
3   strategy1    t4   0.90
4   strategy2   t1   0.40
5   strategy2  t2   0.80
6   strategy2     t3   0.22
7   strategy2    t4   0.95
8   strategy3   t1   0.32
9   strategy3  t2   0.90
10  strategy3     t3   0.25
11  strategy3    t4   0.96
12  strategy4   t1   0.34
13  strategy4  t2   0.88
14  strategy4     t3   0.28
15  strategy4    t4   0.97

set_index( ) 将 DataFrame 中的列转化为行索引:https://blog.csdn.net/u012193416/article/details/83152895

stack('c') 类似于excel 按照c 列汇总:https://www.cnblogs.com/bambipai/p/7658311.html

pandas 入门二_第1张图片

reset_index()  :https://blog.csdn.net/u013630675/article/details/79043648

 

  1.      a    b  c    d  
  2. 0  bar  one  z  1.0  
  3. 1  bar  two  y  2.0  
  4. 2  foo  one  x  3.0  
  5. 3  foo  two  w  4.0  
  6. In [308]: indexed1 = data.set_index('c')  
  7.      a    b    d  
  8. c                 
  9. z  bar  one  1.0  
  10. y  bar  two  2.0  
  11. x  foo  one  3.0  
  12. w  foo  two  4.0  
  13. In [308]: indexed1 = data.reset_index()  
  14.      a    b  c    d  
  15. 0  bar  one  z  1.0  
  16. 1  bar  two  y  2.0  
  17. 2  foo  one  x  3.0  
  18. 3  foo  two  w  4.0

 

你可能感兴趣的:(python)