Appending a list or series to a pandas DataFrame as a row?

后端 未结 12 1993
一向
一向 2020-12-02 05:22

So I have initialized an empty pandas DataFrame and I would like to iteratively append lists (or Series) as rows in this DataFrame. What is the best way of doing this?

12条回答
  •  无人及你
    2020-12-02 05:37

    Here's a function that, given an already created dataframe, will append a list as a new row. This should probably have error catchers thrown in, but if you know exactly what you're adding then it shouldn't be an issue.

    import pandas as pd
    import numpy as np
    
    def addRow(df,ls):
        """
        Given a dataframe and a list, append the list as a new row to the dataframe.
    
        :param df:  The original dataframe
        :param ls:  The new row to be added
        :return:  The dataframe with the newly appended row
        """
    
        numEl = len(ls)
    
        newRow = pd.DataFrame(np.array(ls).reshape(1,numEl), columns = list(df.columns))
    
        df = df.append(newRow, ignore_index=True)
    
        return df
    

提交回复
热议问题