Append an empty row in dataframe using pandas

前端 未结 8 1862
忘了有多久
忘了有多久 2021-02-01 13:25

I am trying to append an empty row at the end of dataframe but unable to do so, even trying to understand how pandas work with append function and still not getting it.

8条回答
  •  孤独总比滥情好
    2021-02-01 14:07

    Append "empty" row to data frame and fill selected cells:

    Generate empty data frame (no rows just columns a and b):

    import pandas as pd    
    col_names =  ["a","b"]
    df  = pd.DataFrame(columns = col_names)
    

    Append empty row at the end of the data frame:

    df = df.append(pd.Series(), ignore_index = True)
    

    Now fill the empty cell at the end (len(df)-1) of the data frame in column a:

    df.loc[[len(df)-1],'a'] = 123
    

    Result:

         a    b
    0  123  NaN
    

    And of course one can iterate over the rows and fill cells:

    col_names =  ["a","b"]
    df  = pd.DataFrame(columns = col_names)
    for x in range(0,5):
        df = df.append(pd.Series(), ignore_index = True)
        df.loc[[len(df)-1],'a'] = 123
    

    Result:

         a    b
    0  123  NaN
    1  123  NaN
    2  123  NaN
    3  123  NaN
    4  123  NaN
    

提交回复
热议问题