【问题标题】:pandas feeding slice as pandas.core.indexes.numeric.Int64Index getting TypeError: slice indices must be integers熊猫将切片作为 pandas.core.indexes.numeric.Int64Index 获取 TypeError:切片索引必须是整数
【发布时间】:2019-01-08 08:14:16
【问题描述】:

我的大脑被锁定了。我收到下面的错误,不明白为什么,索引是 int64 所以??? .我想浏览数据集并找到所有更改的行并将它们的索引位置记录到一个数组中。然后用数组依次去每个位置,打印出接下来的两行就得到下一个位置。

TypeError: slice indices must be integers or None or have an __index__ method

这里是代码段和数据。

import pandas as pd

data = [['edward',1],['edward',0],['edward',0],['norm',1],['norm',0],['norm',0] ]

df_names = pd.DataFrame( data )

criteria = df_names[1] == 1

df_just_changes = df_names[ criteria ]

print(df_names)
print(df_just_changes .index)
print("type of  df_just_changes.index {} ".format(type( df_just_changes.index ) ) )
print("type of  df_just_changes.index[0] {} ".format(type( df_just_changes.index[0] ) ) )
print( df_names.values[df_just_changes.index : 2 ])

【问题讨论】:

  • 你到底想做什么?您是否试图掩盖“已更改”的唯一行?
  • df_just_changes.index 返回一个数组,而不是 int。你想达到什么目的?
  • 对不起,我更改了问题以显示我正在尝试做的事情,即通过更大的数据找到列为 1 的位置,然后打印出接下来的两行,然后返回下一个值在数组中并做同样的事情

标签: python-3.x pandas slice


【解决方案1】:

您也许可以使用蒙版和“fillna”来向前填充(填充)蒙版。 比如:

# make criteria false values NaN
criteria[~criteria] == None
# forward fill the NaNsafter the True values limiting to 2
criteria = criteria.fillna(method="ffill", limit=1)
# whatever's left, make False
criteria = criteria.fillna(False)
# and you mask is complete
df_changed = df_names[criteria]

【讨论】:

  • 谢谢,但我不想那样做。我希望当它们发生变化时我可以找到行的索引(数据集已排序)并使用它直接转到它们并打印出以下两行。
  • 这正是它的作用。条件掩码是更改行的掩码索引,您只需将两行添加到掩码。最好阅读 Pandas 索引。
  • 我同意这就是它的作用,为此我感谢你。我只是不喜欢它的外观。我想使用更改行的索引,然后考虑使用 iloc 来获取接下来的两行。我会听取你的建议并提醒自己这一切是如何运作的。我想这又是块管理器的时候了。感谢您的帮助
  • 您的方法将要求您遍历数据帧,这当然是可能的,但没有利用 pandas 的广播功能
  • 不,它不会迭代,我得到更改字段的索引,将它们放入一个数组中,然后使用该数组直接转到数据索引位置,只需将两个添加到索引指针,从而得到直接的行。请问迭代在哪里?我只是遍历索引位置数组而不是数据本身。
猜你喜欢
  • 2018-04-18
  • 1970-01-01
  • 1970-01-01
  • 2020-08-09
  • 1970-01-01
  • 2021-01-29
  • 2020-09-14
  • 1970-01-01
  • 2019-07-04
相关资源
最近更新 更多