replace rows in a pandas data frame

前端 未结 2 924
Happy的楠姐
Happy的楠姐 2020-12-17 18:36

I want to start with an empty data frame and then add to it one row each time. I can even start with a 0 data frame data=pd.DataFrame(np.zeros(shape=(10,2)),column=[\

相关标签:
2条回答
  • 2020-12-17 18:45

    If you are replacing the entire row then you can just use an index and not need row,column slices. ...

    data.loc[2]=5,6

    0 讨论(0)
  • 2020-12-17 18:46

    Use .loc for label based selection, it is important you understand how to slice properly: http://pandas.pydata.org/pandas-docs/stable/indexing.html#selection-by-label and understand why you should avoid chained assignment: http://pandas.pydata.org/pandas-docs/stable/indexing.html#indexing-view-versus-copy

    In [14]:
    
    data=pd.DataFrame(np.zeros(shape=(10,2)),columns=["a","b"])
    data
    Out[14]:
       a  b
    0  0  0
    1  0  0
    2  0  0
    3  0  0
    4  0  0
    5  0  0
    6  0  0
    7  0  0
    8  0  0
    9  0  0
    
    [10 rows x 2 columns]
    In [15]:
    
    data.loc[2:2,'a':'b']=5,6
    data
    Out[15]:
       a  b
    0  0  0
    1  0  0
    2  5  6
    3  0  0
    4  0  0
    5  0  0
    6  0  0
    7  0  0
    8  0  0
    9  0  0
    
    [10 rows x 2 columns]
    
    0 讨论(0)
提交回复
热议问题