【问题标题】:Converting pandas dataframe into list of tuples with index将熊猫数据框转换为具有索引的元组列表
【发布时间】:2016-12-17 02:16:54
【问题描述】:

我目前正在尝试将 pandas 数据框转换为元组列表。但是,我也很难为元组中的值获取索引(即日期)。我的第一步是到这里,但他们没有向元组添加任何索引。

Pandas convert dataframe to array of tuples

我唯一的问题是访问 numpy 数组中每一行的索引。我有一个如下所示的解决方案,但它使用了一个额外的计数器indexCounter,它看起来很草率。我觉得应该有一个更优雅的解决方案来从特定的 numpy 数组中检索索引。

def get_Quandl_daily_data(ticker, start, end):
prices = []
symbol = format_ticker(ticker)


try:
    data = quandl.get("WIKI/" + symbol, start_date=start, end_date=end)
except Exception, e:
    print "Could not download QUANDL data: %s" % e

subset = data[['Open','High','Low','Close','Adj. Close','Volume']]

indexCounter = 0
for row in subset.values:
    dateIndex = subset.index.values[indexCounter]
    tup = (dateIndex, "%.4f" % row[0], "%.4f" % row[1], "%.4f" % row[2], "%.4f" % row[3], "%.4f" % row[4],row[5])
    prices.append(tup)
    indexCounter += 1

提前感谢您的帮助!

【问题讨论】:

    标签: python pandas numpy tuples


    【解决方案1】:

    你可以遍历to_records(index=True)的结果。

    假设你从这个开始:

    In [6]: df = pd.DataFrame({'a': range(3, 7), 'b': range(1, 5), 'c': range(2, 6)}).set_index('a')
    
    In [7]: df
    Out[7]: 
       b  c
    a      
    3  1  2
    4  2  3
    5  3  4
    6  4  5
    

    那么这可行,只是它不包含索引 (a):

    In [8]: [tuple(x) for x in df.to_records(index=False)]
    Out[8]: [(1, 2), (2, 3), (3, 4), (4, 5)]
    

    但是,如果你通过index=True,那么它会做你想做的事:

    In [9]: [tuple(x) for x in df.to_records(index=True)]
    Out[9]: [(3, 1, 2), (4, 2, 3), (5, 3, 4), (6, 4, 5)]
    

    【讨论】:

    • 感谢您的回复阿米。你的回答很有帮助!但是我很好奇我是否可以使用 reset_index() 函数,因为索引不是任意的。每个指数都是特定股票的开盘价、最高价、最低价、收盘价、成交量数据的日期。所以我想以某种方式使用“子集”numpy数组中使用的先前索引。这还能实现我想要创建的功能吗?
    • @user3547551 我已经稍微缩短了一些步骤,所以它在任何情况下都不会使用reset_index
    猜你喜欢
    • 2014-08-02
    • 2023-03-30
    • 2013-12-26
    相关资源
    最近更新 更多