我有一个数据框如下:
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/