7

I want to append a list of four prices [1, 2, 3, 4] to an already existing dataframe using the DataFrame.append(), the already existing dataframe has four columns.

Using this

dataframe = pd.DataFrame(columns=["open", "high", "low", "close"],
                         data = [[1, 2, 3, 4]])

Creates the dataframe

   open  high  low  close
0     1     2    3      4

Then I want to append some lists like this:

dataframe = dataframe.append([[5, 6, 7, 8]],
                             ignore_index =True)

Gives the output

   open  high  low  close    0    1    2    3
0   1.0   2.0  3.0    4.0  NaN  NaN  NaN  NaN
1   NaN   NaN  NaN    NaN  5.0  6.0  7.0  8.0

While I want the list to be appended in continuation to the dataframe, is there a way to do this without using the column names, only the list of four prices?

buhtz
  • 10,774
  • 18
  • 76
  • 149
Rahul Rai
  • 73
  • 1
  • 1
  • 4
  • First, stop and ask yourself *why are you doing this*. You almost never want to append single rows to a dataframe. – juanpa.arrivillaga Apr 05 '19 at 18:36
  • 1
    Possible duplicate of [Appending a list or series to a pandas DataFrame as a row?](https://stackoverflow.com/questions/26309962/appending-a-list-or-series-to-a-pandas-dataframe-as-a-row) – Querenker Apr 05 '19 at 18:40
  • @juanpa.arrivillaga, I want to do this to convert a time series of tick data into rangebar data, (rangebar are a variant of candlesticks where new candles are only generated when price moves outside a certain range). – Rahul Rai Apr 06 '19 at 07:26

2 Answers2

5

You can do something like

df.loc[len(df)] = [1, 2, 3, 4]
cs95
  • 379,657
  • 97
  • 704
  • 746
Slayer
  • 832
  • 1
  • 6
  • 21
  • 1
    How about if the added row is not complete, `df.loc[len(df)] = [1, 2, 3]` , which would result in size mismatch? – Mohd Jul 03 '20 at 13:43
1

if you will be adding more than one row, you should use the concat function. Which will require you to add the new data in a DataFrame first.

df3 = pd.concat([df1, df2], ignore_index=True)

Read more in the docs here.

mostafazh
  • 4,144
  • 1
  • 20
  • 26