python - 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
我错过了什么?
解决方案
将您的代码更改为
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()
推荐阅读
- arrays - 出现错误:“ARRAY 索引超出语句范围”
- postgresql - 从部署在 Heroku 中的 springboot 连接到我服务器中的 Postgres
- excel - MS Excel 公式:在字符串中查找单词的位置/位置
- slack - 设置当月最后一天的提醒
- cookies - 第三方shopify应用程序中的同一个站点没有不起作用
- python - 高频声音 Python
- webrtc - WebRTCStats - GoogRTT 和 PacketsLost 有时为空
- rust - 使用 postMessage 将 JsValue 对象发送到不同的执行上下文
- linux - Puppet 中具有默认值的复杂结构
- sql - 执行 string_split 时出现 SQL 查询问题