重建索引数据框的问题:重新索引仅对具有唯一值的索引对象有效

msp*_*ino 3 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)
Run Code Online (Sandbox Code Playgroud)

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

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
Run Code Online (Sandbox Code Playgroud)

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

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

Exception: Reindexing only valid with uniquely valued Index objects
Run Code Online (Sandbox Code Playgroud)

但是,如果我对上面两个数据子集做同样的事情,我不会得到错误:

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

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)
Run Code Online (Sandbox Code Playgroud)

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

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)
Run Code Online (Sandbox Code Playgroud)

我真的为此疯狂,并无法理解这一点的原因.似乎数据帧是重复的,并且重复的索引是"干净的"....如果你愿意,我可以提供数据帧的pickle文件.

And*_*den 6

您可以通过索引进行分组并获取第一个条目(请参阅文档):

df.groupby(level=0).first()
Run Code Online (Sandbox Code Playgroud)

例:

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
Run Code Online (Sandbox Code Playgroud)

  • 您可以通过`df.index.get_duplicates()`:)查看重复项的位置 (6认同)