In Python, how to append a list as a row to a Pandas DataFrame ?
There are several ways to append a list to a Pandas Dataframe in Python. Let's consider the following dataframe and list:
import pandas as pd
# Dataframe
df = pd.DataFrame([[1, 2], [3, 4]], columns = ["col1", "col2"])
# List to append
list = [5, 6]
Option 1: append the list at the end of the dataframe with pandas.DataFrame.loc
.
df.loc[len(df)] = list
Option 2: convert the list to dataframe and append with pandas.DataFrame.append()
.
df = df.append(pd.DataFrame([list], columns=df.columns), ignore_index=True)
Option 3: convert the list to series and append withpandas.DataFrame.append()
.
df = df.append(pd.Series(list, index = df.columns), ignore_index=True)
Each of the above options should create a dataframe similar to:
col1 col2
0 1 2
1 3 4
2 5 6