1

When appending to a pandas DataFrame, the appended value doesn't get added to the DataFrame.

I am trying to make an empty DataFrame, and then be able to add more rows onto it, later in my code.

import pandas

df = pandas.DataFrame(columns=["A"])
df.append(DataFrame([[1]]))

print(df)

Output:

Empty DataFrame
Columns: [date, start_time, end_time]
Index: []

Any ideas what I might be doing wrong?

According to the documentation this should work as expected with a new row of value 1 under column A. However, as described above, instead it doesn't append a new row.

Henry Ecker
  • 34,399
  • 18
  • 41
  • 57
  • 1
    `df = df.append(pandas.DataFrame([[1]]))` [append](https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.append.html#pandas-dataframe-append) returns a copy of the dataframe with the new values. – Henry Ecker Jun 19 '21 at 01:53
  • Append has no 'inplace' option (you can't do inplace=True) – 9mjb Jun 19 '21 at 03:30
  • Also, if you are appending to an empty dataframe, you don’t need to assign columns when you create it. – le_camerone Jun 19 '21 at 03:57

1 Answers1

2

As @HenryEcker mentionned to you, append returns a copy of the dataframe with the new values. Your code should be:

import pandas

df = pandas.DataFrame(columns=["A"])
df = df.append(pandas.DataFrame([1], columns=['A']))

print(df)

Output:

   A
0  1
Corralien
  • 109,409
  • 8
  • 28
  • 52
  • Ok thank you! I see, so I need to declare it as the same variable to overwrite it. Is this the most efficient way of doing this? Or would there be any other efficient ways? – Marcel Barlik Jun 19 '21 at 22:01