首页 > 解决方案 > 将一行中的值添加到下一行并删除熊猫数据框中的第一行

问题描述

我有一个看起来像这样的 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

不关心索引。我会改变它们。

谢谢!

标签: pythonpandasindexing

解决方案


假设你的 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

推荐阅读