2016-09-27 264 views
1

我需要將pandas df轉換爲np數組,但我在進程中丟失了列名。我已經閱讀並搜索了一段時間,現在我被卡住了。當我將pandas df轉換爲np數組時,如何保留列名?

我DF看起來是這樣的:

mont_data.tail() 
Out[114]: 
Index  MOEX.ME  ^GSPC  ^MXX  ^N225 ^OSEAX 
Date               
2016-05-31 0.001482 -0.004077 0.002506 -0.000005 0.033240 
2016-06-30 0.074850 0.008136 -0.002262 -0.029029 0.002518 
2016-07-31 0.025882 0.030147 0.024242 0.007169 0.032473 
2016-08-31 0.059069 0.014333 0.025050 0.025243 -0.008767 
2016-09-30 0.035201 -0.009029 -0.016499 -0.039833 -0.003520 

我然後執行:

mont_arr = mont_data.as_matrix(columns=[mont_data.columns[0:5]]) 

或:

mont_arr = mont_data.as_matrix(columns=[mont_data.columns[0:]]) 

兩個結果在NP陣列沒有列標題。任何想法如何解決這個問題?

使用最新版本的軟件包中提到的與Python 3.5

+1

不能做:'numpy'數組沒有頭名。 –

+0

嗯......我要在陣列上做一個np.corrcoef,當沒有名字附加在他們身上時,我怎麼能跟蹤相關係數? – cJc

+0

'mont_data.columns.tolist()'會爲您提供列名。但是你可以使用['DataFrame.corr()'](http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.corr.html)在pandas中進行計算。 –

回答

3

你可以計算列之間的相關係數在大熊貓。

import io 
import pandas as pd 

data = io.StringIO('''\ 
Index  MOEX.ME  ^GSPC  ^MXX  ^N225 ^OSEAX 
2016-05-31 0.001482 -0.004077 0.002506 -0.000005 0.033240 
2016-06-30 0.074850 0.008136 -0.002262 -0.029029 0.002518 
2016-07-31 0.025882 0.030147 0.024242 0.007169 0.032473 
2016-08-31 0.059069 0.014333 0.025050 0.025243 -0.008767 
2016-09-30 0.035201 -0.009029 -0.016499 -0.039833 -0.003520 
''') 
mont_data = pd.read_csv(data, delim_whitespace=True).set_index('Date') 

print(mont_data.corr()) 

輸出:

  MOEX.ME  ^GSPC  ^MXX  ^N225 ^OSEAX 
MOEX.ME 1.000000 0.201809 0.030481 -0.152252 -0.762061 
^GSPC 0.201809 1.000000 0.853232 0.595998 0.261402 
^MXX  0.030481 0.853232 1.000000 0.926106 0.231001 
^N225 -0.152252 0.595998 0.926106 1.000000 0.225621 
^OSEAX -0.762061 0.261402 0.231001 0.225621 1.000000 
+0

...或者'mont_data.iloc [:,1:]。T.corr()'重現'np.corrcoef' –

2

你能做到這樣:

In [19]: df 
Out[19]: 
      MOEX.ME  ^GSPC  ^MXX  ^N225 ^OSEAX 
Date 
2016-05-31 0.001482 -0.004077 0.002506 -0.000005 0.033240 
2016-06-30 0.074850 0.008136 -0.002262 -0.029029 0.002518 
2016-07-31 0.025882 0.030147 0.024242 0.007169 0.032473 
2016-08-31 0.059069 0.014333 0.025050 0.025243 -0.008767 
2016-09-30 0.035201 -0.009029 -0.016499 -0.039833 -0.003520 

In [23]: result = pd.DataFrame(np.corrcoef(df), index=df.columns, columns=df.columns) 

In [24]: result 
Out[24]: 
      MOEX.ME  ^GSPC  ^MXX  ^N225 ^OSEAX 
MOEX.ME 1.000000 -0.087534 0.433865 -0.651299 0.093799 
^GSPC -0.087534 1.000000 0.457119 0.657940 0.980054 
^MXX  0.433865 0.457119 1.000000 -0.299503 0.596537 
^N225 -0.651299 0.657940 -0.299503 1.000000 0.501435 
^OSEAX 0.093799 0.980054 0.596537 0.501435 1.000000 
+0

然後我得到以下錯誤:ValueError:傳遞值的形狀是(121,121),索引暗示(5,121) – cJc

+0

@cJc,我已更新我的答案 - 請試試看... – MaxU

+0

現在我得到:傳遞值的形狀是(121,121),指數暗示(5,) – cJc

相關問題