【问题标题】:Keep only the first row of consecutive duplicate rows in a DataFrame [duplicate]仅保留 DataFrame 中连续重复行的第一行 [重复]
【发布时间】:2015-10-26 14:56:22
【问题描述】:

假设我有一个包含一列数据的 DataFrame。例如:

np.random.random_integers(0,2,1000)
data = np.cumsum(np.random.random_integers(0,2,1000))
idx = pd.date_range('1-1-2001', freq='D', periods=1000)
df = pd.DataFrame(data, idx)

我不想使用完整的 DataFrame,而是只想返回那些与前一行不同的行。

因此,这个

2001-01-20   21
2001-01-21   21
2001-01-22   21
2001-01-23   23
2001-01-24   24
2001-01-25   24

会导致这个

2001-01-20   21
2001-01-23   23
2001-01-24   24

现在我会这样做

dff = df.diff() # Compute another Series with the differences
dff.ix[0, ] = df.ix[0, ] # Instead of NAN for the row use first row of df
df['diff'] = dff # Add as column in df
df = df[df['diff'] >= 1] # Filter out 
df = df.ix[:, 0:-1] # Drop additional column

这看起来非常复杂。我觉得我错过了什么。有什么想法可以让它更 Pythonic 和 Panda-esque 吗?

【问题讨论】:

  • df.drop_duplicates() 有什么问题?你的代码也没有运行,cumsum 定义在哪里?
  • 好的,在这个例子中 df.drop_duplicates 可以工作,但如果我有一个周期性信号。以鼻窦风格为例。在这种情况下,我会错过更改。
  • 对不起,你能用示例代码和期望的输出解释你的意思吗,我真的不清楚
  • 所以您想过滤相差超过 1 的行?
  • 你的问题是不是和这个一样:stackoverflow.com/questions/19463985/…?

标签: python pandas dataframe time-series


【解决方案1】:

您可以使用 .shift() 比较前一行和当前行,然后使用相应的布尔系列索引 DataFrame:

df.loc[df['a'] != df['a'].shift()]

(我假设您的列名为“a”)。

.shift() 只是将列/系列中的值向上或向下移动指定数量的位置(默认为向下 1)。

【讨论】:

    猜你喜欢
    • 2020-11-10
    • 1970-01-01
    • 2017-12-23
    • 2019-09-05
    • 2012-04-30
    • 1970-01-01
    • 2011-08-31
    • 2017-12-29
    • 1970-01-01
    相关资源
    最近更新 更多