仅保留 DataFrame 中连续重复行的第一行

Keep only the first row of consecutive duplicate rows in a DataFrame

假设我有一个包含一列数据的 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,而是只想 return 那些与前一行不同的行。

因此,这

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

这看起来非常复杂。我觉得我错过了什么。有什么想法可以让它更像蟒蛇和熊猫吗?

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

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

(我假设您的专栏名为 'a')。

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