[Python] How do I incrementally add rows in Pandas Dataframe?

Discussão em 'Python' iniciado por Stack, Março 18, 2025.

  1. Stack

    Stack Membro Participativo

    I am calculating the open-high-low-close (OHLC) of data for a duration of each 15 mins from 9:15 to 15:30 and want to store the OHLC values in a dataframe in each new row.

    ohlc = pd.DataFrame(columns=('Open','High','Low','Close'))
    for row in ohlc:
    ohlc.loc[10] = pd.DataFrame([[candle_open_price,candle_high_price,candle_low_price,candle_close_price]])


    But I am not able to do say getting an error of:

    ValueError: cannot set a row with mismatched columns


    Just I want to incrementally store the OHLC data of each 15-minute duration which I have calculated & put in rows of the new ohlc dataframe


    EDIT

    import numpy as np
    import pandas as pd
    import datetime as dt
    import matplotlib as plt
    import dateutil.parser

    tradedata = pd.read_csv('ICICIBANK_TradeData.csv', index_col=False,
    names=['Datetime','Price'],
    header=0)
    tradedata['Datetime'] = pd.to_datetime(tradedata['Datetime'])

    first_trd_time = tradedata['Datetime'][0]
    last_time = dateutil.parser.parse('2016-01-01 15:30:00.000000')

    candle_time = 15;
    candle_number = 0

    while(first_trd_time < last_time):
    candledata = tradedata[(tradedata['Datetime']>first_trd_time) & (tradedata['Datetime']<first_trd_time+dt.timedelta(minutes=candle_time))]
    first_trd_time = first_trd_time+dt.timedelta(minutes=candle_time)

    candle_open_price = candledata.iloc[0]['Price']
    candle_open_time = candledata.iloc[0]['Datetime']
    candle_close_price = candledata.iloc[-1]['Price']
    candle_close_time = candledata.iloc[-1]['Datetime']
    candle_high_price = candledata.loc[candledata['Price'].idxmax()]['Price']
    candle_high_time = candledata.loc[candledata['Price'].idxmax()]['Datetime']
    candle_low_price = candledata.loc[candledata['Price'].idxmin()]['Price']
    candle_low_time = candledata.loc[candledata['Price'].idxmin()]['Datetime']

    ohlc = pd.DataFrame(columns=('Open','High','Low','Close'))
    ohlc_data = pd.DataFrame()

    if(candle_number == 0):
    ohlc = pd.DataFrame(np.array([[0, 0, 0, 0]]), columns=['Open', 'High', 'Low', 'Close']).append(ohlc, ignore_index=True)
    candle_number = candle_number + 1
    print "Zeroth Candle"
    else:
    ohlc.ix[candle_number] = (candle_open_price,candle_open_price,candle_open_price,candle_open_price)
    print "else part with incermenting candle_number"
    candle_number = candle_number + 1

    print "first_trd_time"
    print first_trd_time
    print candle_number

    print "Success!"


    This is my code error is

    ValueError: cannot set by positional indexing with enlargement


    [​IMG]

    Continue reading...

Compartilhe esta Página