首页 > 解决方案 > Pandas 在索引 0 处添加带有虚拟值的行

问题描述

到这个数据框df

        Player   Team  Points  Mean   Price   Value
Gameweek                                                                 
1       Jim  Leeds     4.4   4.40  10.44         0.44
2       Jim  Leeds     8.9   6.65  12.97         2.53
3       Jim  Leeds    -1.8   3.83  10.70        -2.27

我需要在索引 0 处添加一个新行,并用一些虚拟值以及开盘价填充它。为此,我正在尝试:

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

为了结束:

        Player   Team  Points  Mean   Price   Value
Gameweek  
0       Jim  Leeds     0.0   0.0   10.00         0.00                                           
1       Jim  Leeds     4.4   4.40  10.44         0.44
2       Jim  Leeds     8.9   6.65  12.97         2.53
3       Jim  Leeds    -1.8   3.83  10.70        -2.27

但我得到:

df.loc[-1] = [df['Player'].item(), 
return self.values.item()
ValueError: can only convert an array of size 1 to a Python scalar

我错过了什么?

标签: pythonpandas

解决方案


将您的代码更改为

df.loc[0] = [df['Player'].iloc[0], 
                  df['Team'].iloc[0],
                  0.0, 
                  0.0, 
                 (df['Price'].iloc[0] - df['Value'].iloc[0]),
                  0.0] 
df = df.sort_index()

推荐阅读