Pandas: Appending a row to a dataframe and specify its index label

前端 未结 4 1637
忘掉有多难
忘掉有多难 2020-12-12 23:32

Is there any way to specify the index that I want for a new row, when appending the row to a dataframe?

The original documentation provides the following example:

4条回答
  •  [愿得一人]
    2020-12-13 00:03

    The name of the Series becomes the index of the row in the DataFrame:

    In [99]: df = pd.DataFrame(np.random.randn(8, 4), columns=['A','B','C','D'])
    
    In [100]: s = df.xs(3)
    
    In [101]: s.name = 10
    
    In [102]: df.append(s)
    Out[102]: 
               A         B         C         D
    0  -2.083321 -0.153749  0.174436  1.081056
    1  -1.026692  1.495850 -0.025245 -0.171046
    2   0.072272  1.218376  1.433281  0.747815
    3  -0.940552  0.853073 -0.134842 -0.277135
    4   0.478302 -0.599752 -0.080577  0.468618
    5   2.609004 -1.679299 -1.593016  1.172298
    6  -0.201605  0.406925  1.983177  0.012030
    7   1.158530 -2.240124  0.851323 -0.240378
    10 -0.940552  0.853073 -0.134842 -0.277135
    

提交回复
热议问题