python - 当数据框中的列中的值发生变化时查找索引值 - Pandas

标签 python pandas dataframe

我有一个数据框如下:

df1 =

     col_1   val_1
0    4.0     0.89
1    4.0     0.56
2    49.0    0.7
3    49.0    1.23
4    52.0    0.8
5    52.0    0.12
6    32.0    0.5

我想在 col_1 中的值发生变化时找到索引值并放入列表中

我尝试了以下方法:

n_change = (np.where(~df1.col_1.diff(+1).isin([0, np.nan])))

但它返回一个数组元组,很难遍历它。

我想要一个解决方案如下

n_change = [2,4,6]

or 

n_change = array(2,4,6)

有更好的方法吗?

最佳答案

您可以使用:

df.index[df['col_1'].ne(df['col_1'].shift().bfill())]
# or with diff
# df.index[df['col_1'].diff().fillna(0).ne(0)]

输出:Int64Index([2, 4, 6], dtype='int64')

如列表:

df.index[df['col_1'].ne(df['col_1'].shift().bfill())].tolist()

输出:[2, 4, 6]

用你的解决方案:

np.where(~df.col_1.diff().isin([0, np.nan]))[0].tolist()

输出:[2, 4, 6]

关于python - 当数据框中的列中的值发生变化时查找索引值 - Pandas,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/74042960/

相关文章:

python - Pandas 数据框中每两列的总和

python - 在pandas dataframe中堆叠列以实现记录格式

python - 在不同的 scipy ode 求解器之间互换

python - 如何从字典列表转换为字典?

python - boost Python 哈希

python - 使用新数据将列添加到数据帧?

python - xarray 多索引连接的最佳实践

python - 替换 Pandas 数据框中的单元格值

r - 在整个数据帧上使用 ifelse()

python - WLS2 UBUNTU : npm ERR! gyp 错误!堆栈错误 : Can't find Python executable "python", 您可以设置 PYTHON 环境变量。和更多