Python pandas: fill a dataframe row by row

后端 未结 4 1451
[愿得一人]
[愿得一人] 2020-12-12 12:13

The simple task of adding a row to a pandas.DataFrame object seems to be hard to accomplish. There are 3 stackoverflow questions relating to this, none of which

4条回答
  •  我在风中等你
    2020-12-12 12:16

    df['y'] will set a column

    since you want to set a row, use .loc

    Note that .ix is equivalent here, yours failed because you tried to assign a dictionary to each element of the row y probably not what you want; converting to a Series tells pandas that you want to align the input (for example you then don't have to to specify all of the elements)

    In [7]: df = pandas.DataFrame(columns=['a','b','c','d'], index=['x','y','z'])
    
    In [8]: df.loc['y'] = pandas.Series({'a':1, 'b':5, 'c':2, 'd':3})
    
    In [9]: df
    Out[9]: 
         a    b    c    d
    x  NaN  NaN  NaN  NaN
    y    1    5    2    3
    z  NaN  NaN  NaN  NaN
    

提交回复
热议问题