【问题标题】:Python array get positions of value changesPython数组获取值变化的位置
【发布时间】:2014-07-10 12:04:19
【问题描述】:

我正在处理一些通常重复值的大型数组。类似的东西:

data[0] = 10
data[1] = 10
data[2] = 12
data[3] = 12
data[4] = 13
data[5] = 9

有什么方法可以得到值确实发生变化的位置。我的意思是,得到类似的东西:

data[0] = 10
data[2] = 12
data[4] = 13
data[5] = 9

目标是以某种方式压缩数组,以便我可以使用更小的数组。我也一直在看熊猫,但目前没有任何成功。

谢谢,

【问题讨论】:

  • 您尝试过……使用循环吗?
  • 尝试将删除的集合(数据)
  • @sundarnatarajСундар 只会删除不是 OP 要求的重复项,他们想检测数组中的值何时发生变化

标签: python arrays pandas


【解决方案1】:

您可以使用 pandas shiftloc 过滤掉连续的重复项。

In [11]:
# construct a numpy array of data
import pandas as pd
import numpy as np
# I've added some more values at the end here
data = np.array([10,10,12,12,13,9,13,12])
data
Out[11]:
array([10, 10, 12, 12, 13,  9, 13, 12])
In [12]:
# construct a pandas dataframe from this
df = pd.DataFrame({'a':data})
df
Out[12]:
    a
0  10
1  10
2  12
3  12
4  13
5   9
6  13
7  12

In [80]:

df.loc[df.a != df.a.shift()]
Out[80]:
    a
0  10
2  12
4  13
5   9
6  13
7  12
In [81]:

data[np.roll(data,1)!=data]
Out[81]:
array([10, 12, 13,  9, 13, 12])
In [82]:

np.where(np.roll(data,1)!=data)
Out[82]:
(array([0, 2, 4, 5, 6, 7], dtype=int64),)

【讨论】:

  • +1,我认为您必须使用shift(1) 代替shitf(-1) 才能获得OP 更预期的结果。
  • @user3825328 别担心,很高兴我能帮上忙
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-10-01
  • 2015-05-12
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多