python - 将一行中的值添加到下一行并删除熊猫数据框中的第一行
问题描述
我有一个看起来像这样的 DataFrame:
Geo Age 2010 2011 2012
0 toronto -1 ~ 7 2 1 5
1 toronto 0 ~ 4 5 3 4
2 toronto 5 ~ 9 4 5 5
3 bc -1 ~ 7 1 3 2
4 bc 0 ~ 4 2 3 1
5 bc 5 ~ 9 3 1 1
6 mt -1 ~ 7 4 3 4
7 mt 0 ~ 4 2 2 1
8 mt 5 ~ 9 6 6 6
我想摆脱每个城市的 -1~7 行但是想在删除之前将值添加到 0~4 行。
期望的输出:
Geo Age 2010 2011 2012
1 toronto 0 ~ 4 7 4 9
2 toronto 5 ~ 9 4 5 5
4 bc 0 ~ 4 3 6 3
5 bc 5 ~ 9 3 1 1
7 mt 0 ~ 4 6 5 5
8 mt 5 ~ 9 6 6 6
不关心索引。我会改变它们。
谢谢!
解决方案
假设你的 df 是有序的,你可以只使用 np.where 和 shift 的组合,然后过滤
import numpy as np
import pandas as pd
df = pd.DataFrame()
df['Geo'] = ['toronto','toronto','toronto']
df['Age'] = ['-1 ~ 7','0 ~ 4','5 ~ 9']
df['2010'] = [2,5,4]
df['2010'] = np.where(df['Age']=='0 ~ 4',df['2010']+df['2010'].shift(1),df['2010'])
df = df[~(df['Age']=='-1 ~ 7')]
display(df)
Geo Age 2010
1 toronto 0 ~ 4 7.0
2 toronto 5 ~ 9 4.0
推荐阅读
- flutter - 名称 appstate 不是类型,因此不能用作类型参数
- php - 在 ACF Pro 中根据选择值动态创建字段 | WordPress,WooCommerce
- python - PyCharm/IntelliJ 中的红色下划线(未解决的引用)停止工作 - 在我的一些 Anaconda 项目中
- chat - 带有视频自托管的聊天系统
- c++ - 解码使用斐波那契码编码的字符串的最佳方法
- php - 在办公时间修改php日期和时间到工作日PHP
- rust - 无法使用异步演员
- python - 基于python中的模式从文本文件中提取文本
- ruby-on-rails - 通过更新增加模型属性!方法
- c++ - 无法使用 CXX 支持编译 BerkeleyDB