熊猫在索引0添加行

时间:2020-08-11 20:53:06

标签: python pandas

我有一个数据帧df,其中有一行,就像这样:

               Player      Team  Points  Mean  Price  Value
Round                                                              
1              Salah  Liverpool     4.5    4.5   6.89  1.89

现在,我需要在索引0处添加一个空列,其空价格为df['Price'] - df['Value'],价格为{Price} = 5.0,所有其他列值都设置为0.0,最后是所以:

               Player      Team  Points  Mean  Price  Value
Round
0              Salah  Liverpool     0.0    0.0   5.0    0.0                        
1              Salah  Liverpool     4.5    4.5   6.89  1.89

atleta_data.loc[-1] = [df['Player'].item(), 
                       df['Team'].item(),
                       0.0, 
                       0.0, 
                       (df['Price'].item() - df['Value'].item()), 
                       0.0]  
atleta_data.index = atleta_data.index +1  # shifting index
atleta_data = atleta_data.sort_index()  # sorting by index

但是我得到了回合0和2。

              Player      Team  Points  Mean  Price  Value
Round
0              Salah  Liverpool     0.0    0.0   5.0    0.0                        
2              Salah  Liverpool     4.5    4.5   6.89  1.89

我如何在回合中得到0和1?

2 个答案:

答案 0 :(得分:2)

您可以使用.reset_index()

atleta_data = atleta_data.sort_index().reset_index()

答案 1 :(得分:1)

让我们尝试

l = [df['Player'].item(), 
                       df['Team'].item(),
                       0.0, 
                       0.0, 
                       (df['Price'].item() - df['Value'].item()), 
                       0.0]

pd.DataFrame([l],columns=df.columns,index=[0]).append(df)
Out[127]: 
  Player       Team  Points  Mean  Price  Value
0  Salah  Liverpool     0.0   0.0   5.00   0.00
1  Salah  Liverpool     4.5   4.5   6.89   1.89
相关问题