dataframe - 重新索引数据帧时出现问题 : Reindexing only valid with uniquely valued Index objects

标签 dataframe pandas reindex

当我尝试在 pandas 中重新索引数据帧时,我遇到了一个非常奇怪的行为。我的 Pandas 版本是 0.10.0,我使用 Python 2.7。 基本上,当我加载数据框时:

eurusd = pd.DataFrame.load('EUR_USD_30Min.df').drop_duplicates().dropna()

eurusd

<class 'pandas.core.frame.DataFrame'>
DatetimeIndex: 119710 entries, 2003-02-02 17:30:00 to 2012-12-28 17:00:00
Data columns:
open     119710  non-null values
high     119710  non-null values
low      119710  non-null values
close    119710  non-null values
dtypes: float64(4)

然后我尝试在更大的日期范围内重新建立索引:

newindex  = pd.DateRange(datetime.datetime(2002,1,1), datetime.datetime(2012,12,31), offset=pd.datetools.Minute(30))

newindex

<class 'pandas.tseries.index.DatetimeIndex'>
[2002-01-01 00:00:00, ..., 2012-12-31 00:00:00]
Length: 192817, Freq: 30T, Timezone: None

尝试重新索引数据帧时出现奇怪的行为。如果我重新索引数据集的较大部分,我会收到此错误:

eurusd[29558:29560].reindex(index=newindex)

Exception: Reindexing only valid with uniquely valued Index objects

但是,如果我对上述数据的两个子集执行相同的操作,则不会收到错误:

这是第一个子集,没有问题,

eurusd[29558:29559].reindex(index=newindex)

<class 'pandas.core.frame.DataFrame'>
DatetimeIndex: 192817 entries, 2002-01-01 00:00:00 to 2012-12-31 00:00:00
Freq: 30T
Data columns:
open     1  non-null values
high     1  non-null values
low      1  non-null values
close    1  non-null values
dtypes: float64(4)

这是第二个子集,仍然没有问题,

eurusd[29559:29560].reindex(index=newindex)

<class 'pandas.core.frame.DataFrame'>
DatetimeIndex: 192817 entries, 2002-01-01 00:00:00 to 2012-12-31 00:00:00
Freq: 30T
Data columns:
open     1  non-null values
high     1  non-null values
low      1  non-null values
close    1  non-null values
dtypes: float64(4)

我真的对此感到疯狂,无法理解其中的原因。看起来数据帧从重复项和重复索引中“干净”了......如果您愿意,我可以为数据帧提供 pickle 文件。

最佳答案

您可以按索引分组并获取第一个条目(请参阅 docs ):

df.groupby(level=0).first()

示例:

In [1]: df = pd.DataFrame([[1], [2]], index=[1, 1])

In [2]: df
Out[2]: 
   0
1  1
1  2

In [3]: df.groupby(level=0).first()
Out[3]: 
   0
1  1

关于dataframe - 重新索引数据帧时出现问题 : Reindexing only valid with uniquely valued Index objects,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14180615/

相关文章:

python - 按标签系列重新索引 DataFrame 列

在列中第一次出现值后删除行及其后续行(使用 dplyr)

python - 如何将一列中的所有值相互比较

r - 将逗号分隔列表转换为数据框

python - tensorflow 错误 : Invalid argument: shape must be a vector

python - 为 pypy 构建 pandas

Python 数据框复制切片警告

python - pandas 多索引数据框中重新索引子级别

elasticsearch - 具有相同源和目标的Elasticsearch重新索引

r - 计算数据的唯一天数总数