python - 引用 iterrows() 中的下一个索引

标签 python python-3.x pandas dataframe

我有一个 Pandas DataFrame,如下所示:

       top         heading  page_no
0   000000           Intro        0
1   100164         Summary        1
2   100451      Experience        1
3   200131          Awards        2
4   200287         Skills         2
5   300147       Education        3
6   300273          Awards        3
7   300329       Interests        3
8   300434  Certifications        3
9   401135             End        4

我使用了一个过滤器,它使用此数据帧从另一个数据帧获取内容。它需要过滤顶部之间的所有内容,即从 000000 到 100164 等等,直到 300434 到 401135。

for index,row in df_heads.iterrows():
    begin = int(row['top'])
    end = ???
    filter_result = result['data'][(result.top < end) & (result.top > begin)]
    print(row['heading'])
    print(filter_result)
    sections[row['heading']] = filter_result
    end = begin

end应该用什么来初始化,以便我们以正确的方式获取过滤器的内容?

最佳答案

我认为您可以通过 shift 创建新专栏然后根据需要通过 fillna 将最后一个 NaN 替换为 0:

df_heads['shifted_top'] = df_heads['top'].shift(-1).fillna(0)
print (df_heads)
      top         heading  page_no  shifted_top
0       0           Intro        0     100164.0
1  100164         Summary        1     100451.0
2  100451      Experience        1     200131.0
3  200131          Awards        2     200287.0
4  200287          Skills        2     300147.0
5  300147       Education        3     300273.0
6  300273          Awards        3     300329.0
7  300329       Interests        3     300434.0
8  300434  Certifications        3     401135.0
9  401135             End        4          0.0

for index,row in df_heads.iterrows():
    begin = int(row['top'])
    end =  int(row['shifted_top'])
    print (begin, end)

0 100164
100164 100451
100451 200131
200131 200287
200287 300147
300147 300273
300273 300329
300329 300434
300434 401135
401135 0

关于python - 引用 iterrows() 中的下一个索引,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42664418/

相关文章:

python - Pandas 与平均值的百分比差异

python - 如何处理 pandas fillna 中的 `None` 值

python - 如何在训练 XGBoost 模型时使用 GPU?

json - 提取twitter json以使用python进行 Elasticsearch 时映射字段类型

python - 检查另一个列表中的字符串列表中是否存在字符串字符?

python - 当我在 dataframe(pandas) 中设置值时出现错误 : 'Series' objects are mutable, 因此它们无法被散列

python - 如何从pandas数据框中的列值中删除连续的四位数字

python - 使用文字字符串插值或f字符串时出现SyntaxError

非守护线程无限期等待锁时 Python 的 sys.exit 行为

python - 如何生成同时将某些字符串转换为 float 的 Python 字典?