【问题标题】:how to pick out individual columns of numerical values from Datareader pandas?如何从 Datareader pandas 中挑选出单独的数值列?
【发布时间】:2016-02-24 16:38:22
【问题描述】:
import pandas.io.data as web
import datetime
import matplotlib.pyplot as plt


start = datetime.datetime.strptime('2/10/2016', '%m/%d/%Y')
end = datetime.datetime.strptime('2/24/2016', '%m/%d/%Y')
f = web.DataReader(['GOOG','AAPL'], 'yahoo', start, end)
#print 'Volume'


    wha = f[['Adj Close']]   #pick out Adj Close
    x=wha[0,:]               
    print x.shape      


ax = f['Adj Close'].plot(grid=True, fontsize=10, rot=45.)
ax.set_ylabel('Adjusted Closing Price ($)')
plt.legend(loc='upper center', ncol=2, bbox_to_anchor=(0.5,1.1), shadow=True, fancybox=True, prop={'size':10})
#plt.show()

正如您在上面看到的,我试图挑选出个别股票价格的数值来进行数据操作。

#print wha[1,:]
x=wha[0,:]
print x.shape    

我可以将其简化为 9x2 矩阵,其中您有两列用于 GOOG 和 AAPL,每列有 9 个价格。

我试过了

print type(x)

看看是不是

<class 'pandas.core.frame.DataFrame'>

通过

wha2=x.values.tolist()

我能够挑选出股票价格。

我现在有没有一种简单的方法来绘制一只股票的价格(例如单独的 AAPL)与日期?

【问题讨论】:

    标签: python python-2.7 pandas anaconda


    【解决方案1】:

    还有什么比 Pandas 数据框更易于处理的数据操作?!?

    >>> f['Adj Close'].iloc[:8, :2]
                     AAPL        GOOG
    Date                             
    2016-02-10  94.269997  684.119995
    2016-02-11  93.699997  683.109985
    2016-02-12  93.989998  682.400024
    2016-02-16  96.639999  691.000000
    2016-02-17  98.120003  708.400024
    2016-02-18  96.260002  697.349976
    2016-02-19  96.040001  700.909973
    2016-02-22  96.879997  706.460022
    

    从您的面板数据中,我首先选择列Adj Close。然后我使用iloc 进行基于索引的位置过滤,选择第 0-8 行和第 0-1 列。

    为了让 Apple 更贴近:

    >>> f['Adj Close'].loc[:, 'AAPL']
    Date
    2016-02-10    94.269997
    2016-02-11    93.699997
    2016-02-12    93.989998
    2016-02-16    96.639999
    2016-02-17    98.120003
    2016-02-18    96.260002
    2016-02-19    96.040001
    2016-02-22    96.879997
    2016-02-23    94.690002
    Name: AAPL, dtype: float64
    

    这是文档中的索引链接。 http://pandas.pydata.org/pandas-docs/stable/indexing.html#indexing-and-selecting-data

    >>> f['Adj Close'].corr()
             AAPL     GOOG
    AAPL  1.00000  0.87332
    GOOG  0.87332  1.00000
    

    【讨论】:

    • 我明白了。这很棒。另外,如果你想做 pearson 相关,我需要做类似 wha2=x.values.tolist() 的事情来提取数值数据点并计算相关系数,还是有更简单的方法使用 pandas?
    • 感谢您对原始帖子的补充。 f['Adj Close'].loc[:, 'AAPL'] 效果很好。 (我想到了 wha3=f['Adj Close'].iloc[:8, 1:2] 但你的更精简)。由此,您将如何仅提取价格列并将其以列表格式保存,以便您可以这样做(来自 scipy.stats.stats import pearsonr)
    • 我通常只是提取调整后的收盘价并立即执行。 web.DataReader(['GOOG','AAPL'], 'yahoo', start, end)['Adj Close']
    • 有没有办法只提取 web.DataReader(['GOOG','AAPL'], 'yahoo', start, end)['Adj Close'] 的数字数据点,所以我可以随意挑出任意日期的价格吗?我试图将价格列输入 pearsonr
    • f['Adj Close'].loc[:, 'AAPL'].values 给你一个 numpy 数组。如果您只想将它​​们放在普通的 python 列表中,请添加 .tolist()。
    猜你喜欢
    • 2013-05-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-02-08
    • 1970-01-01
    相关资源
    最近更新 更多